﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_DSJCJ.Common;
using System.Data;
using Webdiyer.WebControls.Mvc;
using System.IO;
using System.Text.RegularExpressions;
using com.top.encrypt;
using Newtonsoft.Json;
using ElingOA6_DSJCJ.Models;
using System.Drawing;
using System.Drawing.Imaging;

namespace ElingOA6_DSJCJ.Controllers
{
    /// <summary>
    /// 前台首页
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class IndexController : Controller
    {
        //
        // GET: /Index/
        public BLL.HREmpl empbll = new BLL.HREmpl();
        public string entityNo = GlobalConstant.ENTITYNO;
        public BLL.Calendar calendarbll = new BLL.Calendar();
        private BLL.Entity entityBLL = new BLL.Entity();
        private BLL.Config configBLL = new BLL.Config();
        private BLL.SysPhrase sysPhraseBLL = new BLL.SysPhrase();
        private BLL.ConfigEntry configEntryBLL = new BLL.ConfigEntry();
        private BLL.Common commonBLL = new BLL.Common();
        private BLL.Document documentBLL = new BLL.Document();
        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        private BLL.DocCls docClsBLL = new BLL.DocCls();
        private BLL.DocRecObject docRecObjectBLL = new BLL.DocRecObject();
        private BLL.DocAttach docAttachBLL = new BLL.DocAttach();
        private BLL.DocReadLog docReadLogBLL = new BLL.DocReadLog();
        private BLL.LinkType linkTypeBLL = new BLL.LinkType();
        private BLL.LinkTypeEntry linkTypeEntryBLL = new BLL.LinkTypeEntry();
        private BLL.DocVote docVoteBLL = new BLL.DocVote();
        private BLL.Ad adBLL = new BLL.Ad();
        private BLL.TaxPeriod taxPeriodBLL = new BLL.TaxPeriod();
        private BLL.HRWatchSchedule HRWatchScheduleBLL = new BLL.HRWatchSchedule();
        private BLL.AccManagerDir AccManagerDirBLL = new BLL.AccManagerDir();
        private BLL.AccManagerDoc AccManagerDocBLL = new BLL.AccManagerDoc();
        private BLL.FTP ftpBLL = new BLL.FTP();
        private BLL.SysBasicCodeName SysBasicCodeNameBLL = new BLL.SysBasicCodeName();
        private BLL.SysBasicCodeCls SysBasicCodeCls = new BLL.SysBasicCodeCls();
        public BLL.HRDept HRDeptBLL = new BLL.HRDept();
        private bool isLogin = false;
        /// <summary>
        /// 文明台账BLL
        /// </summary>
        private BLL.AccManagerDoc accManagerDocBLL = new BLL.AccManagerDoc();
        /// <summary>
        /// 系统参数逻辑类
        /// </summary>
        private BLL.SysParam sysParamBLL = new BLL.SysParam();
        /// <summary>
        /// 首页视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            DateTime beginDate = DateTime.Now;
            //Login("admin", "123456");
            getParam();
            string uid = string.Empty;
            string message = ssoUidLogin(ref uid);//是否单点登录跳转
            if (message != string.Empty)
            {
                if (message == "SSOUserBind")
                {
                    return RedirectToAction("SSOUserBind", "Index", new { uid = uid });
                }
                else if (message == "banLogin")
                {
                    message = "用户禁止登录";
                }
                else if (message == "loginPast")
                {
                    message = "用户已过期";
                }
                else if (message == "ipAstrict")
                {
                    message = "ip受限制";
                }

            }

            ViewData["message"] = message;

            if (OperateSession.get("messageLogin") != null)
            {
                ViewData["messageLogin"] = OperateSession.get("messageLogin");
                OperateSession.add("messageLogin", "");
            }
            else
            {
                ViewData["messageLogin"] = "";
            }

            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            string dummyPath = GlobalConstant.DUMMYPATH;
            List<Model.Config> configList = configBLL.GetListAllIsUse(GlobalConstant.ENTITYNO);
            ViewData["configList"] = configList;
            //配置文件明细
            List<Model.ConfigEntry> configEntryList = configEntryBLL.GetModelListWithShowText(GlobalConstant.ENTITYNO, "04");
            ViewData["configEntryList"] = configEntryList;
            List<Model.ConfigEntry> tempEntryList = new List<Model.ConfigEntry>();//存放临时配置文件明细
            Dictionary<string, List<Models.DocumentGridModel>> dicDocumentList = new Dictionary<string, List<Models.DocumentGridModel>>();
            int total = 0;
            dicDocumentList.Add("doc_link2_04", GetDocList("doc_link2", "04", 9, out total, "Y"));//通知公告
            dicDocumentList.Add("doc_link1_042", GetDocList("doc_link1", "04", 9, out total, "Y"));//图片新闻
            total = 0;
            dicDocumentList.Add("doc_link3_04", GetDocList("doc_link3", "04", 6, out total, "Y"));//稽查信息
            total = 0;
            dicDocumentList.Add("doc_link4_04", GetDocList("doc_link4", "04", 6, out total, "Y"));//工作动态
            total = 0;
            dicDocumentList.Add("doc_link5_04", GetDocList("doc_link5", "04", 10, out total, "Y"));//稽查案例库
            total = 0;
            dicDocumentList.Add("doc_link6_04", GetDocList("doc_link6", "04", 6, out total, "Y"));//学习园地
#region 递归通知公告

            List<Model.ConfigEntry> tempEntryLista2 = configEntryList.Where(c => c.FKeyName == "doc_link2" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> ts2 = GetSelfAndChildConfigEntry(configEntryList, tempEntryLista2);
            if (ts2.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in ts2)
                {
                    total = 0;
                    string tempKey = "doc_link2_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link2", "04", 8, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }
#endregion


            #region 递归稽查信息

            List<Model.ConfigEntry> tempEntryLista = configEntryList.Where(c => c.FKeyName == "doc_link3" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> ts = GetSelfAndChildConfigEntry(configEntryList, tempEntryLista);
            if (ts.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in ts)
                {
                    total = 0;
                    string tempKey = "doc_link3_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link3", "04", 8, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }

            #endregion
            #region   递归工作动态


            List<Model.ConfigEntry> tempEntryListab = configEntryList.Where(c => c.FKeyName == "doc_link4" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> tsc = GetSelfAndChildConfigEntry(configEntryList, tempEntryListab);

            if (tsc.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in tsc)
                {
                    total = 0;
                    string tempKey = "doc_link4_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link4", "04", 8, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }


            #endregion

            #region 递归学习园地
            List<Model.ConfigEntry> ta = configEntryList.Where(c => c.FKeyName == "doc_link6" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> tsa = GetSelfAndChildConfigEntry(configEntryList, ta);

            if (tsa.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in tsa)
                {
                    total = 0;
                    string tempKey = "doc_link6_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link6", "04", 9, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }
            #endregion

            List<Model.HRDept> mHRDept = HRDeptBLL.GetAllDeptByEntityNoFIsAgency(entityNo);
            ViewData["HRDept"] = mHRDept;

            List<Models.DocumentGridModel> tpxwList = GetDocList("doc_link1", "04", 5, out total, "Y");
            //获取图片新闻的图片路径
            string pic = "";
            string link = "";
            string text = "";
            int picCount = 1;
            string strSelect_btn = "<ul>";
            string strPicshow_img = "<div><dl class='show'></dl>";

            foreach (Models.DocumentGridModel docGridModel in tpxwList)
            {
                if (picCount < 6)
                {
                    string thumbSrvFileName = documentBLL.GetDocFThumbSrvFileName(entityNo, docGridModel.FDocId);
                    if (thumbSrvFileName != "")
                    {
                        pic = thumbSrvFileName;
                        link = "/Index/DocView?docId=" + docGridModel.FDocId;
                        if (docGridModel.FTitle.Length > 30)
                        {
                            text = docGridModel.FTitle.Substring(0, 30) + "...";
                        }
                        else
                        {
                            text = docGridModel.FTitle;
                        }


                        //if (picCount == 1)
                        //{
                        //    strSelect_btn += "<li>" + picCount + "</li>";
                        //    strPicshow_img += "<dl class='show'>";
                        //}
                        //else
                        //{
                        //    strSelect_btn += "<li>" + picCount + "</li>";
                        //    strPicshow_img += "<dl>";
                        //}
                        strSelect_btn += "<li>" + picCount + "</li>";
                        strPicshow_img += "<dl><dt><a href='" + link + "' title='' target='_blank'><img src='" + pic + "' alt='" + docGridModel.FTitle + "'></a></dt>";
                        strPicshow_img += "<dd><h2><a href='" + link + "' target='_blank'>" + docGridModel.FTitle + "</a></h2></dd></dl>";
                        picCount++;
                    }

                }
            }
            strSelect_btn += "</ul>";
            strPicshow_img += "</div>";

            if (strPicshow_img != "")
            {
                ViewData["Picshow_img"] = strPicshow_img;
            }
            if (strSelect_btn != "")
            {
                ViewData["Select_btn"] = strSelect_btn;
            }

            if (tpxwList.Count > 0)
            {
                Model.Document firstPicDocumentModel = new Model.Document();
                foreach (Models.DocumentGridModel documentModel in tpxwList)
                {
                    if (documentModel.FEditMode == "H")
                    {
                        firstPicDocumentModel = documentBLL.GetModel(documentModel.FDocId);
                        firstPicDocumentModel.FContentTxt = GenerateUtil.NoHTML(firstPicDocumentModel.FContentTxt);

                        break;
                    }
                }
                ViewData["firstPicModel"] = firstPicDocumentModel;
                if (firstPicDocumentModel.FDocId > 0)
                {
                    foreach (Models.DocumentGridModel documentModel in tpxwList)
                    {
                        if (documentModel.FDocId == firstPicDocumentModel.FDocId)
                        {
                            tpxwList.Remove(documentModel);
                        }
                        break;
                    }
                }
                else
                {
                    tpxwList.RemoveAt(tpxwList.Count - 1);
                }
            }
            dicDocumentList.Add("doc_link1_04", tpxwList);//图片新闻


            //获取类别
            //获取搜索类别
            //List<Model. configList.Where(s=>s.FConfigClass=="05").ToList();
            //{
            //    documentList = Model[key];
            //}
            //List<Model.Config> searchList = configList.Where(s => s.FConfigClass == "05").ToList();


            //DataSet docClsDS = docClsBLL.GetAllSubDocCls(null, entityNo);
            //List<SelectListItem> itemList = new List<SelectListItem>();
            //itemList.Add(new SelectListItem() { Text = "--------选择类别--------", Value = "-1" });
            //for (int i = 0; i < docClsDS.Tables[0].Rows.Count; i++)
            //{
            //    DataRow dr = docClsDS.Tables[0].Rows[i];
            //    int level = 0;
            //    if (dr["level"] != null)
            //    {
            //        level = int.Parse(dr["level"].ToString());
            //        string preString = "";
            //        for (int j = 0; j < level; j++)
            //        {

            //            if (j == 0)
            //            {
            //                preString = System.Web.HttpUtility.HtmlDecode("&nbsp;") + "┗";
            //            }
            //            else
            //            {
            //                preString = System.Web.HttpUtility.HtmlDecode("&nbsp;") + preString;
            //            }

            //        }
            //        dr["FDocClsName"] = preString + dr["FDocClsName"].ToString();
            //        itemList.Add(new SelectListItem() { Text = dr["FDocClsName"].ToString(), Value = dr["FDocClsCd"].ToString() });

            //    }

            //}
            //ViewData["clsList"] = searchList;


            ViewData["DeptName"] = "";
            ViewData["EmpName"] = "";
            if (isLogin)
            {

                string loginName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //获取部门信息
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (emplNo != "" && entityNo != "")
                {
                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                break;
                            }

                        }
                    }
                }
                //获取提醒数据
                ViewData["rmdcdr"] = calendarbll.GetModelList("FEmplNo='" + emplNo + "' and FNextWakeTime is not null").Where(h => h.FNextWakeTime < DateTime.Now).OrderBy(h => h.FPri).ToList();

            }
            else
            {
                //未登录提醒数据为空
                ViewData["rmdcdr"] = new List<Model.Calendar>();
            }
            //友情连接
            Dictionary<string, List<Model.LinkTypeEntry>> dicLinkTypeList = new Dictionary<string, List<Model.LinkTypeEntry>>();
            List<Model.LinkType> linkTypeList = linkTypeBLL.GetAllList(entityNo);
            Dictionary<string, string> dicLinkNameList = new Dictionary<string, string>();
            foreach (Model.LinkType linkTypeModel in linkTypeList)
            {
                dicLinkNameList.Add(linkTypeModel.FLinkTypeCD, linkTypeModel.FLinkTypeName);
                dicLinkTypeList.Add(linkTypeModel.FLinkTypeCD, linkTypeEntryBLL.GetListByLinkType(entityNo, linkTypeModel.FLinkTypeCD));
            }
            ViewData["dicLinkTypeList"] = dicLinkTypeList;
            ViewData["dicLinkNameList"] = dicLinkNameList;

            //获取广告信息
            //获取浮动图标
            string strWhere = " FAdProp='1' and FIsUse='1' and FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            ViewData["adFDList"] = adBLL.GetModelList(strWhere);
            //对联广告
            ViewData["adDLList"] = GetDlImage();
            //全屏广告
            strWhere = " (FAdProp='5' or FADProp='2') and FIsUse='1' and FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            ViewData["adQPList"] = adBLL.GetModelList(strWhere);

            //获取专题专栏的数据
            string preDocClsCd = Common.GenerateUtil.GetConfigValue("doc_ztzl_cls");
            Dictionary<string, string> zlOldDic = new Dictionary<string, string>();
            if (preDocClsCd != "")
            {
                zlOldDic = docClsBLL.GetIdAndLogUrl(preDocClsCd, GlobalConstant.ENTITYNO);

            }
            Dictionary<string, string> zlOldDicnew = new Dictionary<string, string>();
            int ztzlcount = Math.Min(3, zlOldDic.Count);
            for (int i = 0; i < ztzlcount; i++)
            {

                zlOldDicnew.Add(zlOldDic.ToList()[i].Key, zlOldDic.ToList()[i].Value);
            }
            ViewData["zlOldDic"] = zlOldDicnew;

            //生日祝福
            string visitIPAddress = Common.GenerateUtil.GetClientIPv4Address();

            DataTable dtBirthEmpl = hrEmplBLL.GetListBirth(" MONTH(FBirthday)=MONTH(GETDATE()) AND DAY(FBirthday)=DAY(GETDATE()) AND FLoginIPAddress='" + visitIPAddress + "'");//获取生日为今日的人
            string strBirth = "";
            foreach (DataRow row in dtBirthEmpl.Rows)
            {
                strBirth += row["FEmpName"].ToString() + ",";
            }
            strBirth = strBirth.Trim(',');
            ViewData["BirthNames"] = strBirth;
            DateTime endDate = DateTime.Now;
            ViewData["RunTime"] = (endDate - beginDate).ToString();
            //获取短句数据
            List<Model.SysPhrase> sysPhraseObj = sysPhraseBLL.GetModelList("FIsTop=1");
            string sysPhrase = string.Empty;
            if (null != sysPhraseObj)
            {
                foreach (Model.SysPhrase s in sysPhraseObj)
                {


                    if (string.IsNullOrEmpty(s.FURL) | s.FURL == "javaccript:;")
                      {
                          sysPhrase += "<span style=\"margin-right: 100px\"><a href='#' target='_self'>" + s.FPhrase + "</a></span>";
                      } 
                      else
                      {
                    
                   
                       // sysPhrase += "<li><a href='" + s.FURL + "' target='_blank'>" + s.FPhrase + "</a></li>";
                        sysPhrase += "<span style=\"margin-right: 100px\"><a href='" + s.FURL + "' target='_blank'>" + s.FPhrase + "</a></span>";
                    
                }  }
            }
            ViewData["phrase"] = sysPhrase;
//             FileStream fs = new FileStream(Server.MapPath(Url.Content("~/Content/birthday/t1.txt")), FileMode.Create);
//            StreamWriter sw = new StreamWriter(fs);
//            sw.Write("wenben=祝：管理员1111");
//            //清空缓冲区
//            sw.Flush();
//            //关闭流
//            sw.Close();
//            fs.Close();
            DateTime now = DateTime.Now;
            int n = (int)now.DayOfWeek;
            string[] weekDays = { "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string nyr = DateTime.Now.ToString("yyyy年MM月dd日") + weekDays[n];
            ViewData["nyr"] = nyr;
            return View("Index", dicDocumentList);
        }

       
        /// <summary>
        /// 获取提醒数据轮询
        /// </summary>
        /// <returns></returns>
        public string needremind()
        {
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            if (!string.IsNullOrEmpty(emplNo))
            {
               

                List<Model.Calendar> mcs = calendarbll.GetModelList("FEmplNo='" + emplNo + "' and FNextWakeTime is not null").Where(h => h.FNextWakeTime < DateTime.Now).OrderBy(h => h.FPri).ToList();
                if (mcs.Count > 0)
                {
                    string success = JsonConvert.SerializeObject(mcs);


                    return success;
                }
                else
                {
                    return "no";
                }
            }
            else
            {
                return "no";
            }
        }




        public ActionResult AdminIndex()
        {
            //Login("admin", "123456");
            getParam();
            string uid = string.Empty;
            string message = ssoUidLogin(ref uid);//是否单点登录跳转
            if (message != string.Empty)
            {
                if (message == "SSOUserBind")
                {
                    return RedirectToAction("SSOUserBind", "Index", new { uid = uid });
                }
                else if (message == "banLogin")
                {
                    message = "用户禁止登录";
                }
                else if (message == "loginPast")
                {
                    message = "用户已过期";
                }
                else if (message == "ipAstrict")
                {
                    message = "ip受限制";
                }

            }

            ViewData["message"] = message;

            if (OperateSession.get("messageLogin") != null)
            {
                ViewData["messageLogin"] = OperateSession.get("messageLogin");
                OperateSession.add("messageLogin", "");
            }
            else
            {
                ViewData["messageLogin"] = "";
            }

            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            string dummyPath = GlobalConstant.DUMMYPATH;
            List<Model.Config> configList = configBLL.GetListAllIsUse(GlobalConstant.ENTITYNO);
            ViewData["configList"] = configList;
            //配置文件明细
            List<Model.ConfigEntry> configEntryList = configEntryBLL.GetModelListWithShowText(GlobalConstant.ENTITYNO, "04");
            ViewData["configEntryList"] = configEntryList;
            List<Model.ConfigEntry> tempEntryList = new List<Model.ConfigEntry>();//存放临时配置文件明细
            Dictionary<string, List<Models.DocumentGridModel>> dicDocumentList = new Dictionary<string, List<Models.DocumentGridModel>>();
            int total = 0;
            dicDocumentList.Add("doc_link2_04", GetDocList("doc_link2", "04", 9, out total, "Y"));//通知公告
            dicDocumentList.Add("doc_link1_042", GetDocList("doc_link1", "04", 9, out total, "Y"));//图片新闻
            total = 0;
            dicDocumentList.Add("doc_link3_04", GetDocList("doc_link3", "04", 6, out total, "Y"));//稽查信息
            total = 0;
            dicDocumentList.Add("doc_link4_04", GetDocList("doc_link4", "04", 6, out total, "Y"));//工作动态
            total = 0;
            dicDocumentList.Add("doc_link5_04", GetDocList("doc_link5", "04", 10, out total, "Y"));//稽查案例库
            total = 0;
            dicDocumentList.Add("doc_link6_04", GetDocList("doc_link6", "04", 6, out total, "Y"));//学习园地
            #region 递归通知公告

            List<Model.ConfigEntry> tempEntryLista2 = configEntryList.Where(c => c.FKeyName == "doc_link2" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> ts2 = GetSelfAndChildConfigEntry(configEntryList, tempEntryLista2);
            if (ts2.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in ts2)
                {
                    total = 0;
                    string tempKey = "doc_link2_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link2", "04", 8, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }
            #endregion

            #region 递归稽查信息

            List<Model.ConfigEntry> tempEntryLista = configEntryList.Where(c => c.FKeyName == "doc_link3" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> ts = GetSelfAndChildConfigEntry(configEntryList, tempEntryLista);
            if (ts.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in ts)
                {
                    total = 0;
                    string tempKey = "doc_link3_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link3", "04", 9, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }

            #endregion
            #region   递归工作动态


            List<Model.ConfigEntry> tempEntryListab = configEntryList.Where(c => c.FKeyName == "doc_link4" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> tsc = GetSelfAndChildConfigEntry(configEntryList, tempEntryListab);

            if (tsc.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in tsc)
                {
                    total = 0;
                    string tempKey = "doc_link4_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link4", "04", 9, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }


            #endregion

            #region 递归学习园地
            List<Model.ConfigEntry> ta = configEntryList.Where(c => c.FKeyName == "doc_link6" && c.FConfigClass == "04").ToList();
            List<Model.ConfigEntry> tsa = GetSelfAndChildConfigEntry(configEntryList, ta);

            if (tsa.Count > 0)
            {
                foreach (Model.ConfigEntry tempEntryModel in tsa)
                {
                    total = 0;
                    string tempKey = "doc_link6_04_" + tempEntryModel.FDocClsCd;
                    dicDocumentList.Add(tempKey, GetDocList("doc_link6", "04", 9, out total, "Y", 1, tempEntryModel.FDocClsCd));
                }
            }
            #endregion

            List<Models.DocumentGridModel> tpxwList = GetDocList("doc_link1", "04", 5, out total, "Y");
            //获取图片新闻的图片路径
            string pic = "";
            string link = "";
            string text = "";
            int picCount = 1;
            string strSelect_btn = "<ul>";
            string strPicshow_img = "<div><dl class='show'></dl>";

            foreach (Models.DocumentGridModel docGridModel in tpxwList)
            {
                if (picCount < 6)
                {
                    string thumbSrvFileName = documentBLL.GetDocFThumbSrvFileName(entityNo, docGridModel.FDocId);
                    if (thumbSrvFileName != "")
                    {
                        pic = thumbSrvFileName;
                        link = "/Index/DocView?docId=" + docGridModel.FDocId;
                        if (docGridModel.FTitle.Length > 30)
                        {
                            text = docGridModel.FTitle.Substring(0, 30) + "...";
                        }
                        else
                        {
                            text = docGridModel.FTitle;
                        }


                        //if (picCount == 1)
                        //{
                        //    strSelect_btn += "<li>" + picCount + "</li>";
                        //    strPicshow_img += "<dl class='show'>";
                        //}
                        //else
                        //{
                        //    strSelect_btn += "<li>" + picCount + "</li>";
                        //    strPicshow_img += "<dl>";
                        //}
                        strSelect_btn += "<li>" + picCount + "</li>";
                        strPicshow_img += "<dl><dt><a href='" + link + "' title='' target='_blank'><img src='" + pic + "' alt='" + docGridModel.FTitle + "'></a></dt>";
                        strPicshow_img += "<dd><h2><a href='" + link + "' target='_blank'>" + docGridModel.FTitle + "</a></h2></dd></dl>";
                        picCount++;
                    }

                }
            }
            strSelect_btn += "</ul>";
            strPicshow_img += "</div>";

            if (strPicshow_img != "")
            {
                ViewData["Picshow_img"] = strPicshow_img;
            }
            if (strSelect_btn != "")
            {
                ViewData["Select_btn"] = strSelect_btn;
            }

            if (tpxwList.Count > 0)
            {
                Model.Document firstPicDocumentModel = new Model.Document();
                foreach (Models.DocumentGridModel documentModel in tpxwList)
                {
                    if (documentModel.FEditMode == "H")
                    {
                        firstPicDocumentModel = documentBLL.GetModel(documentModel.FDocId);
                        firstPicDocumentModel.FContentTxt = GenerateUtil.NoHTML(firstPicDocumentModel.FContentTxt);

                        break;
                    }
                }
                ViewData["firstPicModel"] = firstPicDocumentModel;
                if (firstPicDocumentModel.FDocId > 0)
                {
                    foreach (Models.DocumentGridModel documentModel in tpxwList)
                    {
                        if (documentModel.FDocId == firstPicDocumentModel.FDocId)
                        {
                            tpxwList.Remove(documentModel);
                        }
                        break;
                    }
                }
                else
                {
                    tpxwList.RemoveAt(tpxwList.Count - 1);
                }
            }
            dicDocumentList.Add("doc_link1_04", tpxwList);//图片新闻


            //获取类别
            //获取搜索类别
            //List<Model. configList.Where(s=>s.FConfigClass=="05").ToList();
            //{
            //    documentList = Model[key];
            //}
            //List<Model.Config> searchList = configList.Where(s => s.FConfigClass == "05").ToList();


            //DataSet docClsDS = docClsBLL.GetAllSubDocCls(null, entityNo);
            //List<SelectListItem> itemList = new List<SelectListItem>();
            //itemList.Add(new SelectListItem() { Text = "--------选择类别--------", Value = "-1" });
            //for (int i = 0; i < docClsDS.Tables[0].Rows.Count; i++)
            //{
            //    DataRow dr = docClsDS.Tables[0].Rows[i];
            //    int level = 0;
            //    if (dr["level"] != null)
            //    {
            //        level = int.Parse(dr["level"].ToString());
            //        string preString = "";
            //        for (int j = 0; j < level; j++)
            //        {

            //            if (j == 0)
            //            {
            //                preString = System.Web.HttpUtility.HtmlDecode("&nbsp;") + "┗";
            //            }
            //            else
            //            {
            //                preString = System.Web.HttpUtility.HtmlDecode("&nbsp;") + preString;
            //            }

            //        }
            //        dr["FDocClsName"] = preString + dr["FDocClsName"].ToString();
            //        itemList.Add(new SelectListItem() { Text = dr["FDocClsName"].ToString(), Value = dr["FDocClsCd"].ToString() });

            //    }

            //}
            //ViewData["clsList"] = searchList;


            ViewData["DeptName"] = "";
            ViewData["EmpName"] = "";
            if (isLogin)
            {

                string loginName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //获取部门信息
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (emplNo != "" && entityNo != "")
                {
                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                break;
                            }

                        }
                    }
                }
            }
            //友情连接
            Dictionary<string, List<Model.LinkTypeEntry>> dicLinkTypeList = new Dictionary<string, List<Model.LinkTypeEntry>>();
            List<Model.LinkType> linkTypeList = linkTypeBLL.GetAllList(entityNo);
            Dictionary<string, string> dicLinkNameList = new Dictionary<string, string>();
            foreach (Model.LinkType linkTypeModel in linkTypeList)
            {
                dicLinkNameList.Add(linkTypeModel.FLinkTypeCD, linkTypeModel.FLinkTypeName);
                dicLinkTypeList.Add(linkTypeModel.FLinkTypeCD, linkTypeEntryBLL.GetListByLinkType(entityNo, linkTypeModel.FLinkTypeCD));
            }
            ViewData["dicLinkTypeList"] = dicLinkTypeList;
            ViewData["dicLinkNameList"] = dicLinkNameList;

            //获取广告信息
            //获取浮动图标
            string strWhere = " FAdProp='1' and FIsUse='1' and FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            ViewData["adFDList"] = adBLL.GetModelList(strWhere);
            //对联广告
            ViewData["adDLList"] = GetDlImage();
            //全屏广告
            strWhere = " (FAdProp='5' or FADProp='2') and FIsUse='1' and FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            ViewData["adQPList"] = adBLL.GetModelList(strWhere);

            //获取专题专栏的数据
            string preDocClsCd = Common.GenerateUtil.GetConfigValue("doc_ztzl_cls");
            Dictionary<string, string> zlOldDic = new Dictionary<string, string>();
            if (preDocClsCd != "")
            {
                zlOldDic = docClsBLL.GetIdAndLogUrl(preDocClsCd, GlobalConstant.ENTITYNO);

            }
            Dictionary<string, string> zlOldDicnew = new Dictionary<string, string>();

            for (int i = 0; i < 3; i++)
            {

                zlOldDicnew.Add(zlOldDic.ToList()[i].Key, zlOldDic.ToList()[i].Value);
            }
            ViewData["zlOldDic"] = zlOldDicnew;

            return View("AdminIndex", dicDocumentList);
        }
        public static List<Model.ConfigEntry> GetSelfAndChildConfigEntry(List<Model.ConfigEntry> configEntryList, List<Model.ConfigEntry> tempEntryLista)
        {
            List<Model.ConfigEntry> ts = new List<Model.ConfigEntry>();
            foreach (Model.ConfigEntry c in tempEntryLista)
            {
                if (configEntryList.Exists(g => g.FKeyName == c.FKeyName && g.FPreDocClsCd == c.FDocClsCd) &
                  string.IsNullOrEmpty(c.FPreDocClsCd))
                //!configEntryList.Select(j => j.FPreDocClsCd).Any(q=>configEntryList.Where(h => h.FKeyName == c.FKeyName && h.FPreDocClsCd == c.FDocClsCd).Select(p=>p.FDocClsCd).Contains(q)))
                {
                    List<Model.ConfigEntry> t = configEntryList.Where(h => h.FKeyName == c.FKeyName && h.FPreDocClsCd == c.FDocClsCd).ToList();
                    ts.AddRange(t);

                }
                else
                {
                    if (!ts.Contains(c) & !configEntryList.Exists(g => g.FKeyName == c.FKeyName && g.FPreDocClsCd == c.FDocClsCd) & string.IsNullOrEmpty(c.FPreDocClsCd))
                    {
                        ts.Add(c);
                    }

                }
            }
            return ts.OrderBy(p => p.FSeq).ToList();
        }
        public static List<Model.ConfigEntry> GetSelfAndChildConfigEntrytzgg(List<Model.ConfigEntry> configEntryList, List<Model.ConfigEntry> tempEntryLista)
        {
            List<Model.ConfigEntry> ts = new List<Model.ConfigEntry>();
            foreach (Model.ConfigEntry c in tempEntryLista)
            {
                if (!ts.Contains(c) & string.IsNullOrEmpty(c.FPreDocClsCd))
                {
                    ts.Add(c);
                }
                if (configEntryList.Exists(g => g.FKeyName == c.FKeyName && g.FPreDocClsCd == c.FDocClsCd) &
                  string.IsNullOrEmpty(c.FPreDocClsCd))
                //!configEntryList.Select(j => j.FPreDocClsCd).Any(q=>configEntryList.Where(h => h.FKeyName == c.FKeyName && h.FPreDocClsCd == c.FDocClsCd).Select(p=>p.FDocClsCd).Contains(q)))
                {
                   
                    List<Model.ConfigEntry> t = configEntryList.Where(h => h.FKeyName == c.FKeyName && h.FPreDocClsCd == c.FDocClsCd).ToList();
                    ts.AddRange(t);
                  
                }
               
                   

               
            }
            return ts.OrderBy(p => p.FSeq).ToList();
        }
        public ActionResult IndexDocList(string keyName, string keyClass, string docClsCd = "", int id = 1)
        {
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            int pageSize = 8;
            int total = 0;
            List<Models.DocumentGridModel> docGridList = GetDocList(keyName, keyClass, pageSize, out total, "Y", id, docClsCd);
            PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);
            if (docClsCd != "")
            {
                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                }
            }
            return View(documentList);
        }

        /// <summary>
        /// 获取大屏广告图片
        /// </summary>
        /// <returns></returns>
        private List<Model.Ad> GetDlImage()
        {
            //string strEntityNo = ViewState["EntityNo"].ToString();
            //string dummyPath = GenerateUtil.GetConfigValue("dummyPath");
            string defpath = "/Content/images/nothing.jpg";
            List<Model.Ad> adList = new List<Model.Ad>();
            Model.Ad adModel = new Model.Ad();

            List<Model.Ad> adLeftList = new List<Model.Ad>();
            List<Model.Ad> adRightList = new List<Model.Ad>();
            string strWhere = "  FAdProp='3' and FIsUse='1' and FEntityNo='" + GlobalConstant.ENTITYNO + "'";//左对联广告
            adLeftList = adBLL.GetModelList(1, strWhere, "FAdcd desc");
            string strWhere1 = " FAdProp='4' and FIsUse='1' and FEntityNo='" + GlobalConstant.ENTITYNO + "'";//右对联广告
            adRightList = adBLL.GetModelList(1, strWhere1, "FAdcd desc");
            adModel.rightImageUrl = defpath;
            adModel.leftImageUrl = defpath;
            if (!(adLeftList.Count > 0 && adRightList.Count > 0))//如果左右有一个不存在，则不显示对联广告
            {
                return adList;
            }
            Model.Ad adObject = new Model.Ad();

            adObject = adLeftList[0];
            int imgWidth = null == adObject.FAdWidth ? 0 : adObject.FAdWidth.Value;
            int imgHeight = null == adObject.FAdHeight ? 0 : adObject.FAdHeight.Value;
            adModel.leftImageUrl = adObject.FSvrFileName == "" ? defpath : adObject.FSvrFileName;
            adModel.leftWidth = imgWidth;
            adModel.leftHeight = imgHeight;
            adModel.leftHRef = adObject.FAdUrl;
            if (adObject.FAdUrl.Trim() != "javascript:;")
            {
                adModel.leftTarget = "_blank";
            }
            adObject = adRightList[0];
            int imgWidth1 = null == adObject.FAdWidth ? 0 : adObject.FAdWidth.Value;
            int imgHeight1 = null == adObject.FAdHeight ? 0 : adObject.FAdHeight.Value;
            adModel.rightImageUrl = adObject.FSvrFileName == "" ? defpath : adObject.FSvrFileName;
            adModel.rightWidth = imgWidth1;
            adModel.rightHeight = imgHeight1;
            adModel.rightHRef = adObject.FAdUrl;
            if (adObject.FAdUrl.Trim() != "javascript:;")
            {
                adModel.rightTarget = "_blank";
            }

            adModel.hidCouPleZt = "1";
            ViewData["hidCouPleZt"] = adModel.hidCouPleZt;
            adList.Add(adModel);
            return adList;
        }
        /// <summary>
        /// 后台桌面科室动态
        /// </summary>
        /// <returns></returns>
        public ActionResult DeskKsdt()
        {
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            string dummyPath = GlobalConstant.DUMMYPATH;
            List<Model.Config> configList = configBLL.GetListAllIsUse(GlobalConstant.ENTITYNO);
            ViewData["configList"] = configList;
            Dictionary<string, List<Models.DocumentGridModel>> dicDocumentList = new Dictionary<string, List<Models.DocumentGridModel>>();
            int total = 0;
            dicDocumentList.Add("doc_link5_04", GetDocList("doc_link5", "04", 5, out total, "N"));//科室动态

            return View("DeskKsdt", dicDocumentList);
        }
        /// <summary>
        /// 列表页
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="configClass"></param>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="isHomePage">是否首页</param>
        /// <param name="pageIndex"></param>
        /// <param name="docClsCd"></param>
        /// <returns></returns>
        private List<Models.DocumentGridModel> GetDocList(string keyName, string configClass, int pageSize, out int total, string isHomePage, int pageIndex = 1, string docClsCd = "")
        {
            total = 0;
            List<Models.DocumentGridModel> documentList = new List<Models.DocumentGridModel>();
            Model.Config configModel = configBLL.GetModel(keyName, configClass, GlobalConstant.ENTITYNO);
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            if (configModel != null)
            {
                if (configModel.FIsWithDocCls == "Y")
                {
                    //公共条件
                    // FIsShowHomePage = 'Y' and FRecycle='N' FIsEnroll = 'Y'
                    //if (model.FIsHomePageShowLimit == "Y")
                    //{
                    //strWhere.Append(" AND DATEDIFF(DAY, CONVERT(VARCHAR(10), FValidDate, 120), CONVERT(VARCHAR(10), GETDATE(), 120)) <= 0 ");
                    //}
                    string fieldOrder = " FIsTop DESC,FTopSeq ASC,FDisplayDate";
                    if (isLogin)
                    {
                        //已登录
                        //栏目: 1、不控制查看权限 或者 2、控制查看权限，公开标题 或者 3、控制查看权限，不公开标题，有权限
                        string strWhere = "  ";
                        string fiedls = "*";
                        string tableName = "";
                        if (docClsCd == "")
                        {
                            if (isHomePage == "Y")
                            {
                                tableName = "dbo.fn_GetIndexDocumentALLByCTE_Login('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "','" + empNo + "')";
                            }
                            else
                            {
                                tableName = "dbo.fn_GetListDocumentALLByCTE_Login('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "','" + empNo + "')";

                            }
                        }
                        else
                        {
                            if (isHomePage == "Y")
                            {
                                tableName = "dbo.fn_GetIndexDocument_DocClsCd_ByCTE_Login('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "','" + empNo + "','" + docClsCd + "')";
                            }
                            else
                            {
                                tableName = "dbo.fn_GetListDocument_DocClsCd_ByCTE_Login('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "','" + empNo + "','" + docClsCd + "')";

                            }
                        }
                        DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                        documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);
                    }
                    else
                    {
                        //未登录
                        //栏目：1、不控制查看权限 或者 2、控制查看权限，公开标题
                        string strWhere = "";
                        string fiedls = "*";
                        string tableName = "";
                        if (docClsCd == "")
                        {
                            if (isHomePage == "Y")
                            {
                                tableName = "dbo.fn_GetIndexDocumentALLByCTE_NotLogin('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "')";
                            }
                            else
                            {
                                tableName = "dbo.fn_GetListDocumentALLByCTE_NotLogin('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "')";

                            }
                        }
                        else
                        {
                            if (isHomePage == "Y")
                            {
                                tableName = "dbo.fn_GetIndexDocument_DocClsCd_ByCTE_NotLogin('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "','" + docClsCd + "')";
                            }
                            else
                            {
                                tableName = "dbo.fn_GetListDocument_DocClsCd_ByCTE_NotLogin('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + configClass + "','" + docClsCd + "')";

                            }
                        }
                        DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                        documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

                    }
                }
            }



            return documentList;
        }
        public ActionResult BrowerError()
        {
            return View("BrowerError");
        }
        /// <summary>
        /// 各部门首页
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentIndex(string keyName, string keyClass, string indexClsCd = "")
        {
            ActionResult actionResult = null;
            string entityNo = GlobalConstant.ENTITYNO;
            ViewData["keyName"] = keyName;
            ViewData["keyClass"] = keyClass;
            ViewData["docClsCd"] = indexClsCd;
            Model.Config configModel = configBLL.GetModel(keyName, keyClass, entityNo);
            if (configModel != null)
            {
                if (configModel.FIsWithDocCls == "Y")
                {
                    string docClsHtml = "";
                    //List<Model.ConfigEntry> configEntryList= configEntryBLL.GetModelList(entityNo, keyName, keyClass);
                    DataTable configDocClsDT = configEntryBLL.GetConfigDocCls(entityNo, keyName, keyClass);
                    var tmpDocCls = configDocClsDT.Select("ClsLevel=0").ToList();
                    if (configDocClsDT.Rows.Count == 0)
                    {
                        Response.Write("<script>alert('该信息类别配置无对应栏目信息');</script>");
                        Response.Flush();
                        Response.End();
                    }
                    else
                    {
                        //1.总栏目为1  ，2当前栏目为1而且所有栏目为2，并且当前栏目是单信息
                        if (configDocClsDT.Rows.Count == 1 || (tmpDocCls.Count() == 1 && configDocClsDT.Rows.Count == 2))
                        {
                            //不显示左边的树
                            //ViewData["docClsCd"] = tmpDocCls[0]["FDocClsCd"].ToString();
                            string docClsCd = tmpDocCls[0]["FDocClsCd"].ToString();
                            Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                            if (docClsModel != null)
                            {
                                if (docClsModel.FDocClsProp == "2")
                                {
                                    //单信息
                                    decimal docId = documentBLL.GetDocIdDocClsCd(entityNo, docClsCd);
                                    if (docId > 0)
                                    {
                                        actionResult = DocView(docId);
                                    }
                                }
                            }

                        }
                        else
                        {
                            if (tmpDocCls.Count() == 1)
                            {
                                //去除0层的节点
                                configDocClsDT.Rows.Remove(tmpDocCls[0]);
                                tmpDocCls = configDocClsDT.Select("ClsLevel=1").ToList();
                            }
                            else
                            {
                                tmpDocCls = configDocClsDT.Select("ClsLevel<0 ").ToList();
                                if (tmpDocCls.Count() == 0)
                                {
                                    tmpDocCls = configDocClsDT.Select("ClsLevel=0 ").ToList();
                                }
                                else
                                {
                                    tmpDocCls = configDocClsDT.Select("ClsLevel<0 OR FPreDocClsCd IS NULL OR FPreDocClsCd='001' ", "FSeq,FDocClsCd").ToList();

                                }


                            }
                            //循环绑定
                            if (tmpDocCls.Count() > 0)
                            {
                                docClsHtml += "<ul>";
                                if (indexClsCd == "")
                                {
                                    indexClsCd = tmpDocCls[0]["FDocClsCd"].ToString();
                                }
                                foreach (DataRow dr in tmpDocCls)
                                {
                                    docClsHtml += "<li><h2><a href='/Index/DocumentIndex?keyName=" + keyName +
                                        "&keyClass=" + keyClass + "&indexClsCd=" + dr["FDocClsCd"].ToString() + "&docClsCd=" + dr["FDocClsCd"].ToString()
                                        + "' >" + dr["FDocClsName"].ToString() + "</a></h2></li>";

                                    //docClsHtml += "<li><a href='/Index/DocList?keyName=" + keyName +
                                    //  "&keyClass=" + keyClass + "&docClsCd=" + dr["FDocClsCd"].ToString()
                                    //  + "' target='contentFrm' >" + dr["FDocClsName"].ToString() + "</a></li>";
                                    if (indexClsCd == dr["FDocClsCd"].ToString())
                                    {
                                        //显示选中栏目的下级栏目
                                        SetDocClsHtml(keyName, keyClass, ref docClsHtml, configDocClsDT, dr["FDocClsCd"].ToString());

                                        //如果显示栏目时 单信息，则右边为详细信息页
                                        Model.DocCls showDocClsModel = docClsBLL.GetModel(entityNo, indexClsCd);
                                        if (showDocClsModel != null)
                                        {
                                            if (showDocClsModel.FDocClsProp == "2")
                                            {
                                                //单信息
                                                decimal ShowDocId = documentBLL.GetDocIdDocClsCd(entityNo, indexClsCd);
                                                ViewData["ShowDocId"] = ShowDocId;
                                            }
                                        }


                                    }
                                }

                                docClsHtml += "</ul>";
                            }
                        }
                        if (actionResult == null)
                        {
                            ViewData["docClsHtml"] = docClsHtml;

                            actionResult = View(configModel);
                        }
                    }

                }
                else
                {
                    Response.Write("<script>alert('该信息类别未配置为【需要对应栏目】');window.close();</script>");
                    Response.Flush();
                    Response.End();
                }
            }
            else
            {
                Response.Write("<script>alert('该信息类别配置未定义');window.close();</script>");
                Response.Flush();
                Response.End();
            }
            return actionResult;
        }
        /// <summary>
        /// 信息查询列表
        /// </summary>
        /// <param name="docClsCd"></param>
        /// <param name="keyText"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DocQueryList(string keyName, string keyText, int id = 1)
        {
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            //if (docClsCd == "-1")
            //{
            //    docClsCd = "";
            //}
            string keyClass = "05";
            int pageSize = 15;
            int pageIndex = id;
            int total = 0;
            string entityNo = GlobalConstant.ENTITYNO;
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            List<Models.DocumentGridModel> docGridList = new List<Models.DocumentGridModel>();
            string fieldOrder = " FIsTop DESC,FTopSeq ASC,FPubDate";
            if (isLogin)
            {
                //已登录
                //栏目: 1、不控制查看权限 或者 2、控制查看权限，公开标题 或者 3、控制查看权限，不公开标题，有权限
                string strWhere = "";
                string fiedls = "*";
                string tableName = "";
                if (keyName == "-1")
                {
                    tableName = "dbo.fn_GetIndexQueryDocumentList_Login('" + GlobalConstant.ENTITYNO + "','" + keyClass + "','" + keyText + "','" + empNo + "')";

                }
                else
                {
                    tableName = "dbo.fn_GetIndexQueryDocumentList_ConfigKey_Login('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + "','" + keyClass + "','" + keyText + "','" + empNo + "')";

                }

                //if (docClsCd == "")
                //{
                //    tableName = "dbo.fn_GetIndexQueryDocumentList_Login('" + GlobalConstant.ENTITYNO + "',null,'" + keyText + "','" + empNo + "')";
                //}
                //else
                //{
                //    tableName = "dbo.fn_GetIndexQueryDocumentList_Login('" + GlobalConstant.ENTITYNO + "','" + docClsCd + "','" + keyText + "','" + empNo + "')";

                //}
                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                docGridList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);
            }
            else
            {
                //未登录
                //栏目：1、不控制查看权限 或者 2、控制查看权限，公开标题
                string strWhere = "";
                string fiedls = "*";
                string tableName = "";
                //if (docClsCd == "")
                //{
                //    tableName = "dbo.fn_GetIndexQueryDocumentList_NotLogin('" + GlobalConstant.ENTITYNO + "',null,'" + keyText + "')";
                //}
                //else
                //{
                //    tableName = "dbo.fn_GetIndexQueryDocumentList_NotLogin('" + GlobalConstant.ENTITYNO + "','" + docClsCd + "','" + keyText + "')";

                //}
                if (keyName == "-1")
                {
                    tableName = "dbo.fn_GetIndexQueryDocumentList_NotLogin('" + GlobalConstant.ENTITYNO + "','" + keyClass + "','" + keyText + "')";

                }
                else
                {
                    tableName = "dbo.fn_GetIndexQueryDocumentList_ConfigKey_NotLogin('" + GlobalConstant.ENTITYNO + "','" + keyName + "','" + keyClass + "','" + keyText + "')";

                }
                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                docGridList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

            }
            PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);
            //if (docClsCd != "")
            //{
            //    Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
            //    if (docClsModel != null)
            //    {
            //        ViewData["docClsName"] = docClsModel.FDocClsName;
            //    }
            //}
            //else
            //{
            //    ViewData["docClsName"] = "全部类别";
            //}
            return View(documentList);
        }
        /// <summary>
        ///递归获取目录树(目前只读取一级子目录)
        /// </summary>
        /// <param name="docClsHtml"></param>
        /// <param name="docSubClsList"></param>
        /// <param name="preDocClsNo"></param>
        /// <param name="className"></param>
        private void SetDocClsHtml(string keyName, string keyClass, ref string docClsHtml, DataTable configDocClsDT, string preDocClsNo)
        {
            var tmpDocCls = configDocClsDT.Select("FPreDocClsCd='" + preDocClsNo + "'").ToList();
            if (tmpDocCls.Count() > 0)
            {
                docClsHtml += "<ul class='sup' style='text-indent: 40px;'>";
                foreach (DataRow dr in tmpDocCls)
                {
                    docClsHtml += "<li><a href='/Index/DocList?keyName=" + keyName +
                                        "&keyClass=" + keyClass + "&docClsCd=" + dr["FDocClsCd"].ToString()
                                        + "' target='contentFrm' >" + dr["FDocClsName"].ToString() + "</a></li>";
                    //SetDocClsHtml(docClsHtml, configDocClsDT, dr["FDocClsCd"].ToString());
                }
                docClsHtml += "</ul>";
            }
        }

        /// <summary>
        /// 显示缩略图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult IndexImage(string pt)
        {
            if (!string.IsNullOrEmpty(pt))
            {


                string strNewImgPath = Url.Content(pt);

                if (GenerateUtil.ExistsFile(strNewImgPath))//图片存在
                {
                    int width = 300;
                    int height = 300;
                    byte[] imgs = OperateImg.breviaryImg(width, height, strNewImgPath, 0);

                    Response.AppendHeader("Content-Length", imgs.Length.ToString());

                    //Response.Clear();
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(imgs);
                    Response.End();
                }
                else
                {
                    return View();
                }
            }
            else
            {
                return View();
            }
            return View();

        }




        public ActionResult IndexImageWithDocid(string pt,string docid)
        {
            if (!string.IsNullOrEmpty(pt))
            {


                string strNewImgPath = Url.Content(pt);

                if (GenerateUtil.ExistsFile(strNewImgPath))//图片存在
                {
                      Model.Document documentModel = documentBLL.GetModel(decimal.Parse(docid));
                      if (documentModel != null)
                      {
                          byte[] imgs = null;
                          Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, documentModel.FDocClsCd);
                          int isWater = (int)docClsModel.FIsPicWaterMark;//是否加水印
                          string strWaterMarkPos = docClsModel.FWaterMarkPos;//水印位置
                          int LeftRightMargin = docClsModel.FLeftRightMargin;//水印左右边距
                          int TopBottomMargin = docClsModel.FTopBottomMargin;//水印上下边距
                          int WaterMarkCls = int.Parse(docClsModel.FWaterMarkCls);//水印类型
                          //  int width = 300;
                          //  int height = 300;
                          if (isWater == 1)//加水印 
                          {
                              BLL.Entity entityBll = new BLL.Entity();
                              Model.Entity entityObject = entityBll.GetModel(entityNo);
                              string strWaterImgPath = entityObject.FWaterMarkSvrFileName;//缩略图片路径
                              if (GenerateUtil.ExistsFile(strWaterImgPath))
                              {
                             
                              Image outimg = BreviaryImg.getImgSytnew(System.Drawing.Image.FromFile(Server.MapPath(strNewImgPath)), entityNo, WaterMarkCls, strWaterMarkPos, LeftRightMargin, TopBottomMargin);
                              MemoryStream ms = new MemoryStream();
                              outimg.Save(ms, ImageFormat.Jpeg);
                             imgs = ms.ToArray();
                              
                              } 
                                else  if (WaterMarkCls==2)
                                  {

                                      Image outimg = BreviaryImg.getImgSytnew(System.Drawing.Image.FromFile(Server.MapPath(strNewImgPath)), entityNo, WaterMarkCls, strWaterMarkPos, LeftRightMargin, TopBottomMargin);
                                      MemoryStream ms = new MemoryStream();
                                      outimg.Save(ms, ImageFormat.Jpeg);
                                      imgs = ms.ToArray();
                                  }
                              else
                              {
                                  imgs = OperateImg.breviaryImg(600, 400, strNewImgPath, 2);
                              }
                          }
                          else
                          {   imgs = OperateImg.breviaryImg(600, 400, strNewImgPath, 2);
                          }
                          Response.AppendHeader("Content-Length", imgs.Length.ToString());

                          //Response.Clear();
                          Response.ContentType = "image/jpeg";
                          Response.BinaryWrite(imgs);
                          Response.End();
                      }
                      else
                      {

                          return View();
                      }
                }
                else
                {
                    return View();
                }
            }
            else
            {
                return View();
            }
            return View();

        }
        /// <summary>
        /// 信息列表
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="keyClass"></param>
        /// <param name="docClsCd"></param>
        /// <param name="showLeftDiv">是否显示左边的导航树</param>
        /// <returns></returns>
        public ActionResult DocList(string keyName, string keyClass, string docClsCd = "", string isShowLeftDiv = "N", int id = 1)
        {
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            int pageSize = 20;
            int total = 0;
            List<Models.DocumentGridModel> docGridList = GetDocList(keyName, keyClass, pageSize, out total, "N", id, docClsCd);
            PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);
            if (docClsCd != "")
            {
                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                    ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                }
            }
            else
            {
                if (isShowLeftDiv == "N")
                {
                    Model.Config configModel = configBLL.GetModel(keyName, keyClass, entityNo);
                    if (configModel != null)
                    {
                        ViewData["docClsName"] = configModel.FShowText;
                        ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                    }
                    else
                    {
                        ViewData["docClsName"] = "";
                        ViewData["navi"] = "";
                    }
                }
                else
                {
                    Model.Config configModel = configBLL.GetModel(keyName, keyClass, entityNo);
                    if (configModel != null)
                    {
                        ViewData["docClsName"] = configModel.FShowText;
                        ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                    }
                }

            }
            return View(documentList);
        }
        /// <summary>
        /// 打印页面
        /// </summary>
        /// <param name="docId"></param>
        /// <returns></returns>
        public ActionResult DocViewPrint(decimal docId)
        {
            DocView(docId, "DocViewPrint");
            return View("DocViewPrint");
        }
        /// <summary>
        /// 获取对应类别的模版顶部图片路径
        /// </summary>
        /// <param name="docClsModel"></param>
        /// <returns></returns>
        public string GetTemplTopPicPath(Model.DocCls docClsModel)
        {
            string imgPath = "";
            //获取最上级有模板顶部图片路径的栏目
            string ztzlDoc = System.Configuration.ConfigurationManager.AppSettings["doc_ztzl_cls"];
            if (docClsModel.FPreDocClsCd != ztzlDoc)
            {
                Model.DocCls tmpDocClsModel = new Model.DocCls();
                tmpDocClsModel = docClsBLL.GetModel(docClsModel.FEntityNo, docClsModel.FPreDocClsCd);
                while (tmpDocClsModel != null && !string.IsNullOrEmpty(tmpDocClsModel.FPreDocClsCd) && string.IsNullOrEmpty(tmpDocClsModel.FTemplTopPicPath))
                {
                    tmpDocClsModel = docClsBLL.GetModel(tmpDocClsModel.FEntityNo, tmpDocClsModel.FPreDocClsCd);
                }
                if (tmpDocClsModel != null)
                {
                    imgPath = tmpDocClsModel.FTemplTopPicPath;
                }
            }
            else
            {
                imgPath = docClsModel.FTemplTopPicPath;
            }
            return imgPath;
        }

        /// <summary>
        /// 查看信息
        /// </summary>
        /// <param name="docID"></param>
        /// <returns></returns>
        public ActionResult DocView(decimal docId, string viewName = "", string viewDocClsCd = "")
        {
            ViewData["docClsCd"] = viewDocClsCd;
            ViewData["logUrl"] = "";//专题专栏top图片地址
            string entityNo = GlobalConstant.ENTITYNO;
            Model.Document documentModel = documentBLL.GetModel(docId);
            if (documentModel != null)
            {

                Model.DocCls docClsModel1 = docClsBLL.GetModel(entityNo, documentModel.FDocClsCd);
                if (docClsModel1 != null)
                {
                    ViewData["docName"] = docClsModel1.FDocClsName;
                }
                ViewData["FDocId"] = documentModel.FDocId;
                ViewData["navi"] = "当前位置：首页 > " + ViewData["docName"].ToString();
                //发布部门名称
                BLL.HRDept hrDeptBLL = new BLL.HRDept();
                documentModel.FDeptName = hrDeptBLL.GetDeptName(entityNo, documentModel.FDeptNo);
                //发布人
                BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
                documentModel.FEmpName = hrEmplBLL.GetEmpName(entityNo, documentModel.FEmplNo);
                //获取信息类别
                string docClsCd = "";
                if (viewDocClsCd != "")//如果是专题专栏
                {
                    docClsCd = viewDocClsCd;
                }
                else
                {
                    docClsCd = documentModel.FDocClsCd;
                }

                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                    ViewData["logUrl"] = GetTemplTopPicPath(docClsModel);
                    ViewData["userSubTitle"] = docClsModel.FUseSubTitle;
                    ViewData["isReferenceNo"] = docClsModel.FIsReferenceNo;
                    string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    bool isLook = true;//是否可查看
                    bool isAddReadLog = false;//是否需要插入信息文档查看记录
                    string url = "";
                    string newofficetype = "1";//默认office文档类型
                   documentModel.FContentTxt = documentModel.FContentTxt.Replace("&nbsp;&nbsp;&nbsp;&nbsp;", "　");//替换成中文的空格
                    //上传图片
                    List<Model.DocAttach> docAttachPicList = docAttachBLL.GetDocAttachListByDocID(docId, "PIC");
                    string strView = "";
                    if (docAttachPicList.Count > 0)
                    {
                        strView += "<div style='text-align: center'>";
                        foreach (Model.DocAttach docAttachModel in docAttachPicList)
                        {
                            strView += "<img alt='' src='" + Url.Action("IndexImageWithDocid", "Index", new { pt = docAttachModel.FAttachSvrFileName, docid = docId }) + "' /><br /><br />";
                        }
                        strView += "</div>";
                    }
                    documentModel.FContentTxt = strView + documentModel.FContentTxt;

                    if (documentModel.FIsEnroll == "N" || documentModel.FRecycle == "Y")
                    {
                        isLook = false;
                    }
                    else
                    {

                        //是否控制查看权限
                        if (docClsModel.FIsCtrlLookAuthority == "Y")
                        {
                            if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                            {
                                //控制到信息 everyone可见的
                                if (docClsModel.FLookAuthorityMode == "D" && documentBLL.IsDocumentAuthorityForEveryone(docId))
                                {
                                    isLook = true;
                                }
                                else
                                {
                                    isLook = false;
                                    Response.Write("<script>alert('请先登录');window.close();</script>");
                                    Response.Flush();
                                    Response.End();
                                    return null;
                                }
                            }
                            else
                            {
                                //判断是否控制到信息
                                if (docClsModel.FLookAuthorityMode == "D")
                                {
                                    if (documentBLL.IsDocumentAuthorityForEmpl(empNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }

                                }
                                else//控制到栏目
                                {
                                    if (documentBLL.IsDocAuthorityForEmpl(empNo, docClsCd, entityNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //判断是否通知对象
                            if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                            {
                                isAddReadLog = true;
                            }
                        }
                    }
                    if (!isLook)
                    {
                        Response.Write("<script>alert('你无权限查看该信息');window.close();</script>");
                        Response.Flush();
                        Response.End();
                        return null;
                    }
                    else
                    {
                        if (documentModel.FEditMode == "O")
                        {
                            url = "/" + documentModel.FSvrFileName.Substring(1);
                            string extension = url.Substring(url.LastIndexOf('.') + 1).ToUpper();
                            switch (extension)
                            {
                                case "DOC":
                                    newofficetype = "1";
                                    break;
                                case "DOCX":
                                    newofficetype = "1";
                                    break;
                                case "XLS":
                                    newofficetype = "2";
                                    break;
                                case "XLSX":
                                    newofficetype = "2";
                                    break;
                                case "PPT":
                                    newofficetype = "3";
                                    break;
                                case "PPTX":
                                    newofficetype = "3";
                                    break;
                                default:
                                    newofficetype = "1";
                                    break;
                            }

                        }

                        //获取权属
                        BLL.Entity entityBLL = new BLL.Entity();
                        ViewData["CopyRight"] = entityBLL.GetCopyRight(GlobalConstant.ENTITYNO);

                        //附件
                        List<Model.DocAttach> docAttachList = docAttachBLL.GetDocAttachListByDocID(docId, "DOC");// attachBll.GetList(GlobalConstant.CONSTRING_ENTITYNO, docID, "DOC");

                        ViewData["docAttach"] = docAttachList;
                        try
                        {
                            documentBLL.UpdateReadCntByDocId(docId); //更新查看次数
                            documentModel.FReadCnt++;
                        }
                        catch
                        {

                        }

                        ViewData["url"] = url;
                        ViewData["newofficetype"] = newofficetype;

                        if (null == OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION) || null == OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY))
                        {
                            //从数据库获取Ntko Office控件序列号
                            BLL.Entity entityBll = new BLL.Entity();
                            Model.Entity entityModel = entityBll.GetModel(GlobalConstant.ENTITYNO);
                            if (entityModel != null)
                            {
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                            }
                        }


                        ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
                        ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);

                        if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                        {
                            //未登录

                        }
                        else
                        {
                            //已登录
                            //获取部门信息
                            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            string deptName = "";
                            string empName = "";
                            if (emplNo != "" && entityNo != "")
                            {
                                DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    DataTable dt = ds.Tables[0];
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                                        {
                                            ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                            ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                            deptName = ViewData["DeptName"].ToString();
                                            empName = ViewData["EmpName"].ToString();
                                            OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                            break;
                                        }

                                    }
                                }
                            }
                            if (isAddReadLog)
                            {
                                //判断是否已经阅读
                                if (!docReadLogBLL.Exists(entityNo, docId, empNo))
                                {
                                    //插入信息文档查看记录
                                    Model.DocReadLog docReadLogModel = new Model.DocReadLog();
                                    docReadLogModel.FEntityNo = entityNo;
                                    docReadLogModel.FDocId = docId;
                                    docReadLogModel.FDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                    docReadLogModel.FDeptName = deptName;
                                    docReadLogModel.FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                                    docReadLogModel.FEmpName = empName;
                                    docReadLogModel.FReadTime = DateTime.Now;
                                    docReadLogModel.FIPAddr = Request.UserHostAddress;
                                    try
                                    {
                                        docReadLogBLL.Add(docReadLogModel);
                                    }
                                    catch
                                    {

                                    }
                                }
                            }
                        }
                        ViewData["isVote"] = docClsModel.FIsVote;


                        //获取批示权限
                        if (docClsModel.FIsExamine == "Y")
                        {
                            BLL.PrvUser prvUserBll = new BLL.PrvUser();
                            Model.PrvUser prvUserModel = prvUserBll.GetModel(OperateSession.get(GlobalConstant.PARAM_LOGINID), GlobalConstant.ENTITYNO);
                            string fisIns = "";
                            if (prvUserModel != null)
                            {
                                fisIns = prvUserModel.FIsInstruct;
                            }
                            ViewData["FIsInstruct"] = fisIns == null ? "" : fisIns;
                            ViewData["FEmplNo"] = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            if (ViewData["FEmplNo"] == null)
                            {
                                ViewData["FEmplNo"] = "";
                            }

                            //获取领导批示列表
                            BLL.LeadInstruct leadInstructBLL = new BLL.LeadInstruct();
                            string strWhere = "FDocId=" + documentModel.FDocId + " and a.FEntityNo='" + GlobalConstant.ENTITYNO + "'";
                            DataSet dslt = leadInstructBLL.GetList(strWhere);
                            ViewData["leadInstruct"] = dslt;
                            ViewData["FDocId"] = documentModel.FDocId;
                        }

                        ViewData["FIsExamine"] = docClsModel.FIsExamine != "Y" ? "N" : "Y";

                        //处理图片
                        string pattern1 = "width\\s?=\\s?\"(\\d+)\"\\s+height\\s?=\\s?\"(\\d+)";
                        string pattern2 = "width\\s?:\\s?(\\d+)px;\\s+height\\s?:\\s?(\\d+)px";
                        int matchType = 0;
                        //利用正则替换内容模块
                        MatchCollection tdMatchs = Regex.Matches(documentModel.FContentTxt,
                        @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>",
                        RegexOptions.IgnoreCase | RegexOptions.Multiline);

                        for (int i = tdMatchs.Count - 1; i >= 0; i--)
                        {
                            string oldimgUrl = tdMatchs[i].Value;
                            MatchCollection tdMatchsTmp = Regex.Matches(oldimgUrl,
                        pattern1, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            if (tdMatchsTmp.Count == 0)
                            {
                                tdMatchsTmp = Regex.Matches(oldimgUrl,
                       pattern2, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                matchType = 2;
                            }
                            else
                            {
                                matchType = 1;
                            }
                            if (tdMatchsTmp.Count > 0)
                            {

                                string imgSizeValue = tdMatchsTmp[0].Value;
                                string width = tdMatchsTmp[0].Groups[1].Value; //宽    
                                string height = tdMatchsTmp[0].Groups[2].Value; //高 
                                int _width = 0;
                                int _height = 0;
                                int newWidth = 0;
                                int newHeight = 0;
                                if (int.TryParse(width, out _width) && int.TryParse(height, out _height))
                                {
                                    if (_width > GlobalConstant.IMG_SHOW_MAXWIDTH)
                                    {
                                        newWidth = GlobalConstant.IMG_SHOW_MAXWIDTH;
                                        newHeight = (_height * GlobalConstant.IMG_SHOW_MAXWIDTH) / _width;
                                        string newImgUrl = "";
                                        if (matchType == 1)
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width='" + newWidth + "' height='" + newHeight + "'");
                                        }
                                        else
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width:" + newWidth + "px; height:" + newHeight + "px");
                                        }
                                        documentModel.FContentTxt = documentModel.FContentTxt.Replace(oldimgUrl, newImgUrl);
                                    }
                                }

                            }
                        }


                        //获取此文档被引用的栏目
                        BLL.DocRefImp docRefImp = new BLL.DocRefImp();
                        List<Model.DocRefImp> docRefImpList = docRefImp.GetListByDocId(GlobalConstant.ENTITYNO, docId);
                        string docRefImpClsName = "";
                        if (docRefImpList.Count > 0)
                        {
                            List<CommonValueModel> commValueList = new List<CommonValueModel>();
                            foreach (Model.DocRefImp docRefImpModel in docRefImpList)
                            {
                                commValueList.Add(new CommonValueModel { Text = docRefImpModel.FDocClsName, Value = docRefImpModel.FDocClsCd });
                                docRefImpClsName += docRefImpModel.FDocClsName + ",";
                            }

                            if (docRefImpClsName != "")
                            {
                                docRefImpClsName = "此信息已被下列栏目引用：" + docRefImpClsName.Trim(',');
                            }

                            ViewData["docRefImpClsName"] = docRefImpClsName;
                            ViewData["docRefImpClsJson"] = JsonConvert.SerializeObject(commValueList);
                        }
                        else
                        {
                            ViewData["docRefImpClsName"] = "";
                            ViewData["docRefImpClsJson"] = "";
                        }




                        if (viewName == "")
                        {
                            return View("DocView", documentModel);
                        }
                        else
                        {
                            return View(viewName, documentModel);
                        }
                    }

                }
                else
                {
                    Response.Write("<script>alert('对应信息类别不存在');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }

            }
            else
            {
                Response.Write("<script>alert('信息不存在');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }
        /// <summary>
        /// 附件下载
        /// </summary>
        /// <param name="attachID"></param>
        /// <returns></returns>
        public ActionResult AttachDownLoad(decimal attachID)
        {
            //BLL.docAttach attachBll = new BLL.docAttach();
            List<string> list = docAttachBLL.GetSvrFileNameAndOldName(attachID);
            if (list.Count == 2)
            {
                string filePath = Server.MapPath(list[0]);

                return new Common.FileResult() { FilePaht = filePath, FileName = list[1] };

            }
            else
            {
                Response.Write("<script>alert('附件不存在');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }


        }




        /// <summary>
        /// 信息列表 机构简介专用
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="keyClass"></param>
        /// <param name="docClsCd"></param>
        /// <param name="showLeftDiv">是否显示左边的导航树</param>
        /// <returns></returns>
        public ActionResult DocJGJJList(string keyName, string keyClass, string docClsCd = "", string isShowLeftDiv = "N", int id = 1)
        {
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            int pageSize = 20;
            int total = 0;
            List<Models.DocumentGridModel> docGridList = GetDocList(keyName, keyClass, pageSize, out total, "N", id, docClsCd);
            PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);
            if (docClsCd != "")
            {
                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                    ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                }
            }
            else
            {
                if (isShowLeftDiv == "N")
                {
                    Model.Config configModel = configBLL.GetModel(keyName, keyClass, entityNo);
                    if (configModel != null)
                    {
                        ViewData["docClsName"] = configModel.FShowText;
                        ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                    }
                    else
                    {
                        ViewData["docClsName"] = "";
                        ViewData["navi"] = "";
                    }
                }

            }
            return View(documentList);
        }




        /// <summary>
        /// 查看信息,机构简介专用
        /// </summary>
        /// <param name="docID"></param>
        /// <returns></returns>
        public ActionResult DocJGJJView(decimal docId, string viewName = "")
        {
            ViewData["logUrl"] = "";//专题专栏top图片地址
            string entityNo = GlobalConstant.ENTITYNO;
            Model.Document documentModel = documentBLL.GetModel(docId);
            if (documentModel != null)
            {
                //发布部门名称
                BLL.HRDept hrDeptBLL = new BLL.HRDept();
                documentModel.FDeptName = hrDeptBLL.GetDeptName(entityNo, documentModel.FDeptNo);
                //发布人
                BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
                documentModel.FEmpName = hrEmplBLL.GetEmpName(entityNo, documentModel.FEmplNo);
                //获取信息类别
                string docClsCd = documentModel.FDocClsCd;

                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                    ViewData["logUrl"] = GetTemplTopPicPath(docClsModel);
                    string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    bool isLook = true;//是否可查看
                    bool isAddReadLog = false;//是否需要插入信息文档查看记录
                    string url = "";
                    string newofficetype = "1";//默认office文档类型
                    documentModel.FContentTxt = documentModel.FContentTxt.Replace("&nbsp;&nbsp;&nbsp;&nbsp;", "　");//替换成中文的空格
                    if (documentModel.FIsEnroll == "N" || documentModel.FRecycle == "Y")
                    {
                        isLook = false;
                    }
                    else
                    {

                        //是否控制查看权限
                        if (docClsModel.FIsCtrlLookAuthority == "Y")
                        {
                            if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                            {
                                isLook = false;
                            }
                            else
                            {
                                //判断是否控制到信息
                                if (docClsModel.FLookAuthorityMode == "D")
                                {
                                    if (documentBLL.IsDocumentAuthorityForEmpl(empNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }

                                }
                                else//控制到栏目
                                {
                                    if (documentBLL.IsDocAuthorityForEmpl(empNo, docClsCd, entityNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //判断是否通知对象
                            if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                            {
                                isAddReadLog = true;
                            }
                        }
                    }
                    if (!isLook)
                    {
                        Response.Write("<script>alert('你无权限查看该信息');window.close();</script>");
                        Response.Flush();
                        Response.End();
                        return null;
                    }
                    else
                    {
                        if (documentModel.FEditMode == "O")
                        {
                            url = "/" + documentModel.FSvrFileName.Substring(1);
                            string extension = url.Substring(url.LastIndexOf('.') + 1).ToUpper();
                            switch (extension)
                            {
                                case "DOC":
                                    newofficetype = "1";
                                    break;
                                case "DOCX":
                                    newofficetype = "1";
                                    break;
                                case "XLS":
                                    newofficetype = "2";
                                    break;
                                case "XLSX":
                                    newofficetype = "2";
                                    break;
                                case "PPT":
                                    newofficetype = "3";
                                    break;
                                case "PPTX":
                                    newofficetype = "3";
                                    break;
                                default:
                                    newofficetype = "1";
                                    break;
                            }

                        }

                        //获取权属
                        BLL.Entity entityBLL = new BLL.Entity();
                        ViewData["CopyRight"] = entityBLL.GetCopyRight(GlobalConstant.ENTITYNO);

                        //附件
                        List<Model.DocAttach> docAttachList = docAttachBLL.GetDocAttachListByDocID(docId, "DOC");// attachBll.GetList(GlobalConstant.CONSTRING_ENTITYNO, docID, "DOC");

                        ViewData["docAttach"] = docAttachList;
                        try
                        {
                            documentBLL.UpdateReadCntByDocId(docId); //更新查看次数
                            documentModel.FReadCnt++;
                        }
                        catch
                        {

                        }

                        ViewData["url"] = url;
                        ViewData["newofficetype"] = newofficetype;

                        if (null == OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION) || null == OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY))
                        {
                            //从数据库获取Ntko Office控件序列号
                            BLL.Entity entityBll = new BLL.Entity();
                            Model.Entity entityModel = entityBll.GetModel(GlobalConstant.ENTITYNO);
                            if (entityModel != null)
                            {
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                            }
                        }


                        ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
                        ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);

                        if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                        {
                            //未登录

                        }
                        else
                        {
                            //已登录
                            //获取部门信息
                            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            string deptName = "";
                            string empName = "";
                            if (emplNo != "" && entityNo != "")
                            {
                                DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    DataTable dt = ds.Tables[0];
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                                        {
                                            ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                            ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                            deptName = ViewData["DeptName"].ToString();
                                            empName = ViewData["EmpName"].ToString();
                                            OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                            break;
                                        }

                                    }
                                }
                            }
                            if (isAddReadLog)
                            {
                                //判断是否已经阅读
                                if (!docReadLogBLL.Exists(entityNo, docId, empNo))
                                {
                                    //插入信息文档查看记录
                                    Model.DocReadLog docReadLogModel = new Model.DocReadLog();
                                    docReadLogModel.FEntityNo = entityNo;
                                    docReadLogModel.FDocId = docId;
                                    docReadLogModel.FDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                    docReadLogModel.FDeptName = deptName;
                                    docReadLogModel.FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                                    docReadLogModel.FEmpName = empName;
                                    docReadLogModel.FReadTime = DateTime.Now;
                                    docReadLogModel.FIPAddr = Request.UserHostAddress;
                                    try
                                    {
                                        docReadLogBLL.Add(docReadLogModel);
                                    }
                                    catch
                                    {

                                    }
                                }
                            }
                        }
                        ViewData["isVote"] = docClsModel.FIsVote;

                        //处理图片
                        string pattern1 = "width\\s?=\\s?\"(\\d+)\"\\s+height\\s?=\\s?\"(\\d+)";
                        string pattern2 = "width\\s?:\\s?(\\d+)px;\\s+height\\s?:\\s?(\\d+)px";
                        int matchType = 0;
                        //利用正则替换内容模块
                        MatchCollection tdMatchs = Regex.Matches(documentModel.FContentTxt,
                        @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>",
                        RegexOptions.IgnoreCase | RegexOptions.Multiline);

                        for (int i = tdMatchs.Count - 1; i >= 0; i--)
                        {
                            string oldimgUrl = tdMatchs[i].Value;
                            MatchCollection tdMatchsTmp = Regex.Matches(oldimgUrl,
                        pattern1, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            if (tdMatchsTmp.Count == 0)
                            {
                                tdMatchsTmp = Regex.Matches(oldimgUrl,
                       pattern2, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                matchType = 2;
                            }
                            else
                            {
                                matchType = 1;
                            }
                            if (tdMatchsTmp.Count > 0)
                            {

                                string imgSizeValue = tdMatchsTmp[0].Value;
                                string width = tdMatchsTmp[0].Groups[1].Value; //宽    
                                string height = tdMatchsTmp[0].Groups[2].Value; //高 
                                int _width = 0;
                                int _height = 0;
                                int newWidth = 0;
                                int newHeight = 0;
                                if (int.TryParse(width, out _width) && int.TryParse(height, out _height))
                                {
                                    if (_width > GlobalConstant.IMG_SHOW_MAXWIDTH)
                                    {
                                        newWidth = GlobalConstant.IMG_SHOW_MAXWIDTH;
                                        newHeight = (_height * GlobalConstant.IMG_SHOW_MAXWIDTH) / _width;
                                        string newImgUrl = "";
                                        if (matchType == 1)
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width='" + newWidth + "' height='" + newHeight + "'");
                                        }
                                        else
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width:" + newWidth + "px; height:" + newHeight + "px");
                                        }
                                        documentModel.FContentTxt = documentModel.FContentTxt.Replace(oldimgUrl, newImgUrl);
                                    }
                                }

                            }
                        }
                        if (viewName == "")
                        {
                            return View("DocJGJJView", documentModel);
                        }
                        else
                        {
                            return View(viewName, documentModel);
                        }
                    }

                }
                else
                {
                    Response.Write("<script>alert('对应信息类别不存在');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }

            }
            else
            {
                Response.Write("<script>alert('信息不存在');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }













        /// <summary>
        /// 文档局长批示
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string DocLeadInstruct(string docid, string content)
        {
            docid = Fetch.estimateString(docid, CheckGetEnum.Safety);
            content = Fetch.estimateString(content, CheckGetEnum.Safety);
            string val = string.Empty;
            if (docid == string.Empty || content == string.Empty)
            {
                return "empty";
            }
            else
            {

                BLL.LeadInstruct LeadInstructBll = new BLL.LeadInstruct();
                Model.LeadInstruct LeadInstructModel = new Model.LeadInstruct();

                LeadInstructModel.FDocId = decimal.Parse(docid);
                LeadInstructModel.FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (LeadInstructModel.FEmplNo == null)
                {
                    LeadInstructModel.FEmplNo = "";
                }
                LeadInstructModel.FDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
             //   LeadInstructModel.FEntityNo = OperateSession.get(GlobalConstant.ENTITYNO);
                LeadInstructModel.FEntityNo = GlobalConstant.ENTITYNO;
                LeadInstructModel.FExamineDate = DateTime.Now;
                LeadInstructModel.FExamineIP = Request.UserHostAddress;
                LeadInstructModel.FExamineContent = content;
                bool boolvalue = false;
             //   bool boo = LeadInstructBll.Exists(decimal.Parse(docid), OperateSession.get(GlobalConstant.PARAM_DEPTNO), OperateSession.get(GlobalConstant.ENTITYNO), OperateSession.get(GlobalConstant.PARAM_FEMPLNO));
                bool boo = LeadInstructBll.Exists(decimal.Parse(docid), OperateSession.get(GlobalConstant.PARAM_DEPTNO), GlobalConstant.ENTITYNO, OperateSession.get(GlobalConstant.PARAM_FEMPLNO));
                if (boo == true)
                {
                    boolvalue = LeadInstructBll.Update(LeadInstructModel);
                }
                else
                {
                    boolvalue = LeadInstructBll.Add(LeadInstructModel);
                    BLL.Document documentBll = new BLL.Document();
                    documentBll.UpdateFisInstruct(docid, OperateSession.get(GlobalConstant.ENTITYNO), "Y");
                }
                if (boolvalue == true)
                {
                    return "yes";
                }
                else
                {
                    return "no";
                }
            }
        }
        /// <summary>
        /// 获取批示内容
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetInstruct(string docid)
        {
            docid = Fetch.estimateString(docid, CheckGetEnum.Safety);
            string val = string.Empty;
            if (docid == string.Empty)
            {
                return "empty";
            }
            else
            {

                BLL.LeadInstruct LeadInstructBll = new BLL.LeadInstruct();
                Model.LeadInstruct LeadInstructModel = new Model.LeadInstruct();
                LeadInstructModel = LeadInstructBll.GetModel(decimal.Parse(docid), OperateSession.get(GlobalConstant.PARAM_DEPTNO), OperateSession.get(GlobalConstant.ENTITYNO), OperateSession.get(GlobalConstant.PARAM_FEMPLNO));
                string strCon = "empty";
                if (LeadInstructModel != null)
                {
                    strCon = LeadInstructModel.FExamineContent;
                }

                return strCon;
            }
        }
        /// <summary>
        /// 删除领导批示
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string DelInstruct(string docid)
        {
            docid = Fetch.estimateString(docid, CheckGetEnum.Safety);
            string val = string.Empty;
            if (docid == string.Empty)
            {
                return "empty";
            }
            else
            {

                BLL.LeadInstruct LeadInstructBll = new BLL.LeadInstruct();
                bool boo = LeadInstructBll.Delete(decimal.Parse(docid), OperateSession.get(GlobalConstant.PARAM_DEPTNO), OperateSession.get(GlobalConstant.ENTITYNO), OperateSession.get(GlobalConstant.PARAM_FEMPLNO));
                if (boo == true)
                {
                    BLL.Document documentBll = new BLL.Document();
                    if (!LeadInstructBll.Exists(decimal.Parse(docid), OperateSession.get(GlobalConstant.ENTITYNO)))
                    {
                        documentBll.UpdateFisInstruct(docid, OperateSession.get(GlobalConstant.ENTITYNO), "N");
                    }
                    return "删除成功";
                }
                else
                {
                    return "删除失败";
                }
            }
        }


        /// <summary>
        /// 信息投票
        /// </summary>
        /// <param name="docId"></param>
        /// <returns></returns>
        [HttpPost]
        public string DocumentVote(decimal docId)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            Model.Document documentModel = documentBLL.GetModel(docId);
            if (documentModel != null)
            {
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (!string.IsNullOrEmpty(emplNo))
                {

                    Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, documentModel.FDocClsCd);
                    if (docClsModel != null)
                    {
                        if (docClsModel.FIsVote == "Y")
                        {
                            //判断ip是否已经投票过了
                            string ipAddress = GenerateUtil.GetClientIPv4Address();
                            bool isExists = docVoteBLL.Exists(entityNo, emplNo);
                            if (!isExists)
                            {
                                Model.DocVote docVoteModel = new Model.DocVote()
                                {
                                    FDocId = docId,
                                    FEmplNo = emplNo,
                                    FEntityNo = entityNo,
                                    FVoteDate = DateTime.Now,
                                    FVoteIP = ipAddress
                                };
                                try
                                {
                                    docVoteBLL.Add(docVoteModel);
                                    jsonstr = "SUCCESS";
                                }
                                catch (Exception ee)
                                {
                                    errorMessage = "投票出错，错误信息:" + ee.Message;
                                }
                            }
                            else
                            {
                                errorMessage = "对不起！您本月已使用过1次投票权";
                            }
                        }
                        else
                        {
                            errorMessage = "信息对应的栏目不需要参与投票";
                        }
                    }
                    else
                    {
                        errorMessage = "信息对应的栏目不存在";
                    }

                }
                else
                {
                    errorMessage = "请先登录再投票";
                }
            }
            else
            {
                errorMessage = "对应信息不存在";
            }
            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        private ActionResult Login()
        {

            bool isSuccess = true;
            string errorMessage = "";
            string loginID = Fetch.Post("txtUserName").Trim();
            if (loginID == "")
            {
                errorMessage = "用户名不能为空！";
                isSuccess = false;
            }
            if (isSuccess)
            {
                string password = Fetch.Post("txtPassword").Trim();

                int result = 0;
                string entityNo = GlobalConstant.ENTITYNO;

                result = SysLogin(loginID, password, entityNo);

                if (result == 1)
                {
                    errorMessage = "用户名或密码错误请重新填写！";
                    isSuccess = false;
                }
                else if (result == 2)
                {
                    errorMessage = "你的帐号已经被禁止登陆！";
                    isSuccess = false;
                }
                else if (result == 3)
                {

                    errorMessage = "你的用户名已过期，不能登陆！";
                    isSuccess = false;
                }
                else if (result == 4)
                {
                    errorMessage = "ip受限制,请联系管理员!";
                }
                else if (result == 200)
                {
                    errorMessage = "";
                }
            }

            ViewData["UserName"] = loginID;
            if (errorMessage != "")
            {
                ViewData["jsAlert"] = errorMessage;
                return Index();// View("index");
            }
            else
            {

                ActionResult actionResult = null;

                BLL.Index adminIndexBLL = new BLL.Index();

                List<Model.PrvFunctList> prvFunctListList = new List<Model.PrvFunctList>();
                if (loginID == "admin")
                {
                    prvFunctListList = adminIndexBLL.GetPrvFunctList();
                }
                else
                {
                    prvFunctListList = adminIndexBLL.GetPrvFunctList(loginID);
                }
                OperateSession.addList(GlobalConstant.PARAM_PRVFUNCTIONLIST, prvFunctListList);

                //ActionResult actionResult = null;
                //Response.Write("<script>window.location.href='/Index';window.open('/ElingOA6_Admin/')</script>");
                // Response.Write("<script>window.location.href='/ElingOA6_Admin_hzwxq/';</script>");
                //Response.Write("<script>window.location.href='/Index/';</script>");
                //Response.Flush();
                //Response.End();

                //return null;
                actionResult = Redirect(Url.Action("Index", "Index"));
                return actionResult;
            }

        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private int SysLogin(string loginID, string password, string entityNo)
        {

            BLL.PrvUser adminLoginBLL = new BLL.PrvUser();
            Model.PrvUser prvUserModel = adminLoginBLL.GetModelByNameAndPassword(loginID, password, entityNo);
            if (prvUserModel == null) //用户名或密码错误
            {
                return 1;
            }
            else
            {
                if (prvUserModel.FProhibitLogin == 1)
                {
                    return 2;
                }
                else if (prvUserModel.FForeverAvailable != 0)//如果账号不是永久有效，就判断该账号是否已过期
                {
                    DateTime timenow = DateTime.Now.AddDays(-1);
                    if (timenow > prvUserModel.FAvailableDate)//已过期
                    {
                        return 3;
                    }
                }
                OperateSession.add(GlobalConstant.PARAM_LOGINID, prvUserModel.FLogID);//把登陆ID保存到Session
                OperateSession.add(GlobalConstant.PARAM_USERNAME, prvUserModel.FUserName);//登陆用户名称
                OperateSession.add(GlobalConstant.PARAM_SYSYEAR, DateTime.Now.Year.ToString());


                OperateSession.add("EntityNo", prvUserModel.FEntityNo);//公司编码
                OperateSession.add("FEmplNo", prvUserModel.FEmplNo);//员工编号




                //从数据库获取Ntko Office控件序列号
                BLL.Entity entityBll = new BLL.Entity();
                Model.Entity entityModel = entityBll.GetModel(prvUserModel.FEntityNo);
                if (entityModel != null)
                {
                    OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                    OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                }


                OperateSession.add(GlobalConstant.PARAM_FEMPLNO, prvUserModel.FEmplNo);
                prvUserModel.FLastLoginIPAddr = Common.GenerateUtil.GetClientIPv4Address();
                adminLoginBLL.UpdateUserLoginMsg(prvUserModel.FLogID, prvUserModel.FLastLoginIPAddr, prvUserModel.FEmplNo, prvUserModel.FLastLoginIPAddr);


                return 200;
            }

        }
        /// <summary>
        /// 检验是否到下班时间
        /// </summary>
        /// <returns></returns>
        public string IsCheck()
        {
            string str = "Y";
            BLL.Attendance attendanceBLL = new BLL.Attendance();
            string today = DateTime.Now.Date.ToString();
            DataSet dsWorkTimePMAttendance = attendanceBLL.GetWorkTimePMAttendance(today);
            string workTimePMattendance = dsWorkTimePMAttendance.Tables[0].Rows[0]["FPMAttendanceTime"].ToString();
            if (DateTime.Parse(DateTime.Now.ToString("HH:mm")) < DateTime.Parse(workTimePMattendance))
            {
                str = "现在服务器时间是" + DateTime.Now.ToString("HH:mm") + "，未到下班时间，是否确认签退？";
            }
            return str;
        }
        /// <summary>
        /// 考勤
        /// </summary>
        /// <returns></returns>
        public string Attendance()
        {
            BLL.Attendance attendanceBLL = new BLL.Attendance();
            string str = "";
            bool isSuccess = true;
            string loginID = OperateSession.get(GlobalConstant.PARAM_LOGINID);
            string entityNo = GlobalConstant.ENTITYNO;
            string userName = OperateSession.get(GlobalConstant.PARAM_USERNAME);

            bool amAT = false;
            bool pmAT = false;
            string minutes = "";
            string today = DateTime.Now.Date.ToString();
            string middleTime = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " " + "12:00";
            //签到显示时间
            if (DateTime.Parse(middleTime) > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm")))
            {
                amAT = true;
            }
            //签退显示时间
            if (DateTime.Parse(middleTime) <= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm")))
            {
                pmAT = true;
            }

            if (loginID == null)
            {
                str = "请先登录";
                isSuccess = false;
            }
            if (isSuccess)
            {
                string attendanceFtatus = hrEmplBLL.GetIsAttendance(entityNo, loginID);
                if (attendanceFtatus == "N")
                {
                    str = "您不用参加网上考勤或者请联系管理员在后台帮您设置需要考勤";
                    return str;
                }
                else
                {
                    bool isCheckAttendace = true;
                    //判断考勤绑定IP是否和当前登录IP一致
                    string attendanceIpAddress = hrEmplBLL.GetAttendanceIpAddress(entityNo, loginID);
                    if (attendanceIpAddress != "")
                    {
                        if (attendanceIpAddress != Common.GenerateUtil.GetClientIPv4Address())
                        {
                            isCheckAttendace = false;
                        }
                    }

                    if (!isCheckAttendace)
                    {
                        str = "请回自己的电脑进行签到签退";
                    }
                    else
                    {
                        Model.Attendance attendanceModel = new Model.Attendance();
                        attendanceModel = attendanceBLL.GetModel(loginID, today);
                        minutes = sysParamBLL.GetParamValue("OA_Attendance_Minutes", entityNo);
                        DateTime attendanceTime = new DateTime();
                        if (attendanceModel != null)
                        {
                            if (minutes != "")
                            {
                                attendanceTime = attendanceModel.FAttendanceTime.AddMinutes(double.Parse(minutes));
                            }
                            else
                            {
                                attendanceTime = attendanceModel.FAttendanceTime;
                            }
                        }
                        else
                        {
                            attendanceTime = DateTime.Now;
                        }
                        if (attendanceTime <= DateTime.Now)
                        {
                            try
                            {
                                attendanceModel = new Model.Attendance();
                                attendanceModel.FAttendanceTime = DateTime.Now;
                                attendanceModel.FAttendanceIP = Common.GenerateUtil.GetClientIPv4Address();
                                attendanceModel.FDeptNo = hrEmplBLL.GetEmplFromViewByEmplNo(loginID, entityNo).Tables[0].Rows[0]["FDeptNo"].ToString();
                                attendanceModel.FEmplNo = loginID;
                                attendanceModel.FEntityNo = entityNo;
                                attendanceBLL.Add(attendanceModel);
                                //更新ip地址绑定
                                try
                                {
                                    if (attendanceIpAddress == "")
                                    {
                                        hrEmplBLL.UpdateAttendanceIpAddress(entityNo, loginID, Common.GenerateUtil.GetClientIPv4Address());
                                    }
                                }
                                catch
                                {
                                }

                                if (amAT)
                                {
                                    attendanceModel = attendanceBLL.GetModelASC(loginID, today);
                                    str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm") + "签到";
                                }
                                if (pmAT)
                                {
                                    attendanceModel = attendanceBLL.GetModel(loginID, today);
                                    str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm")
                                        + "签退,请确认签退时间，如果签退有误，请在" + attendanceModel.FAttendanceTime.AddMinutes(int.Parse(minutes)).ToString("HH:mm") + "后重新签退";
                                }
                            }
                            catch (Exception)
                            {
                                str = "签到失败";
                            }
                        }
                        else
                        {
                            if (amAT)
                            {
                                attendanceModel = attendanceBLL.GetModelASC(loginID, today);
                                str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm") + "签到,不用重复签到";
                            }
                            if (pmAT)
                            {

                                attendanceModel = attendanceBLL.GetModel(loginID, today);
                                str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm")
                                    + "签退,请确认签退时间，如果签退有误，请在" + attendanceModel.FAttendanceTime.AddMinutes(int.Parse(minutes)).ToString("HH:mm") + "后重新签退";
                            }
                        }
                    }
                }
            }

            return str;
        }

        /// <summary>
        /// 退出
        /// </summary>
        public void LogExit()
        {

            OperateSession.del(GlobalConstant.PARAM_USERNAME);
            OperateSession.del(GlobalConstant.PARAM_LOGINID);
            Session.Clear();
            Response.Write("<script>window.location.href='/'</script>");
            Response.Flush();
            Response.End();
        }
        /// <summary>
        /// 头部
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 1, VaryByParam = "none")]
        public ActionResult Top()
        {
            List<Model.Config> configList = configBLL.GetListAllIsUse(GlobalConstant.ENTITYNO);

            //首页时间显示
            DateTime currentDate = commonBLL.GetServerDateTime();
            ViewData["ndate"] = currentDate.ToString("yyyy年MM月dd日") + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek);

            return PartialView(configList);

        }
        /// <returns></returns>
        [OutputCache(Duration = 1, VaryByParam = "none")]
        public ActionResult AdminTop()
        {
            List<Model.Config> configList = configBLL.GetListAllIsUse(GlobalConstant.ENTITYNO);

            //首页时间显示
            DateTime currentDate = commonBLL.GetServerDateTime();
            ViewData["ndate"] = currentDate.ToString("yyyy年MM月dd日") + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek);

            return PartialView(configList);

        }
        /// <summary>
        /// 底部
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 1, VaryByParam = "none")]
        public ActionResult Bottom()
        {
            string entityNo = GlobalConstant.ENTITYNO;


            ViewData["CopyRight"] = entityBLL.GetCopyRight(GlobalConstant.ENTITYNO);
            return PartialView();
        }

        public ActionResult UploadLook(string Fid)
        {
            bool alllook = false;
            string entityNo = GlobalConstant.ENTITYNO;
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;

            if (isLogin)
            {
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (ftpBLL.FIsAllowLookFtpOrAllowByDept(Fid, emplNo, entityNo))
                {
                    alllook = true;
                }
                else
                {
                    alllook = false;
                }
                ViewData["DeptName"] = "";
                ViewData["EmpName"] = "";


                string loginName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //获取部门信息

                if (emplNo != "" && entityNo != "")
                {
                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["empName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["FEmplNo"] = dt.Rows[i]["FEmplNo"].ToString();
                                ViewData["deptName"] = dt.Rows[i]["FDeptName"].ToString();
                                ViewData["deptNo"] = dt.Rows[i]["FDeptNo"].ToString();
                                OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                break;
                            }

                        }
                    }
                }

                //string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                //string deptName = OperateSession.get(GlobalConstant.PARAM_DEPTNAME);
                //string FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                //string empName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //ViewData["empName"] = empName;
                //ViewData["FEmplNo"] = FEmplNo;
                //ViewData["deptNo"] = deptNo;
                //ViewData["deptName"] = deptName;
                List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                ViewData["SysBasicCodeName"] = cmlist;
                Model.FTP mftp = ftpBLL.GetModel(decimal.Parse(Fid));

                ViewData["FFtpShowText"] = entityBLL.GetAllList().Tables[0].Rows[0]["FFtpShowText"].ToString();
                string strwhere = " and  FId=" + Fid + " and dbo.t_ftp.FEntityNo=" + entityNo;
                DataTable dtfile = ftpBLL.GetFtpAndDocAttach(strwhere).Tables[0];
                Dictionary<string, string> attachfiles = new Dictionary<string, string>();
                foreach (DataRow fr in dtfile.Rows)
                {
                    attachfiles.Add(fr["FAttachID"].ToString(), fr["FAttachOldFileName"].ToString());
                }
                ViewData["alllook"] = alllook;
                ViewData["attachfiles"] = attachfiles;
                return View("UploadLook", mftp);



            }
            else
            {

                Response.Write("<script>alert('请先登录');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }

        public ActionResult LoginUpload()
        {
            string entityNo = GlobalConstant.ENTITYNO;
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;

            if (isLogin)
            {

                ViewData["DeptName"] = "";
                ViewData["EmpName"] = "";
                if (isLogin)
                {

                    string loginName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                    //获取部门信息
                    string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    if (emplNo != "" && entityNo != "")
                    {
                        DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            DataTable dt = ds.Tables[0];
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                                {
                                    ViewData["empName"] = dt.Rows[i]["FEmpName"].ToString();
                                    ViewData["FEmplNo"] = dt.Rows[i]["FEmplNo"].ToString();
                                    ViewData["deptName"] = dt.Rows[i]["FDeptName"].ToString();
                                    ViewData["deptNo"] = dt.Rows[i]["FDeptNo"].ToString();
                                    OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                    break;
                                }

                            }
                        }
                    }
                }

             //if (! HRDeptBLL.IsFIsAgencyByDeptNo(ViewData["deptNo"].ToString()))
             //{
             //    Response.Write("<script>alert('您所在的部门不能上传文件');window.close();</script>");
             //    Response.Flush();
             //    Response.End();
             //    return null;
             //}
               
                //string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                //string deptName = OperateSession.get(GlobalConstant.PARAM_DEPTNAME);
                //string FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                //string empName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //ViewData["empName"] = empName;
                //ViewData["FEmplNo"] = FEmplNo;
                //ViewData["deptNo"] = deptNo;
                //ViewData["deptName"] = deptName;
                List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                ViewData["SysBasicCodeName"] = cmlist;

                ViewData["FFtpShowText"] = entityBLL.GetAllList().Tables[0].Rows[0]["FFtpShowText"].ToString();
                return View("LoginUpload");
            }
            else
            {
                Response.Write("<script>alert('请先登录');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }

        }

        public ActionResult SaveUpload()
        {
            try
            {
                string deptName = Fetch.Post("deptName");
                string FLinkTel = Fetch.Post("FLinkTel");
                string FLinkMan = Fetch.Post("FLinkMan");
                string FFTPType = Fetch.Post("FFTPType");
                string FSubject = Fetch.Post("FSubject");
                string deptNo = Fetch.Post("hdeptNo");
                string FEmplNo = Fetch.Post("hFEmplNo");
                Model.FTP f = new Model.FTP();
                f.FDeptNo = deptNo;
                f.FEmplNo = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_FEMPLNO)) ? FEmplNo : OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                f.FFTPType = FFTPType;
                f.FInputTime = DateTime.Now;
                f.FLinkMan = FLinkMan;
                f.FLinkTel = FLinkTel;
                f.FEntityNo = GlobalConstant.ENTITYNO;
                f.FSubject = FSubject;


                ftpBLL.Add(f);

                string entityNo = GlobalConstant.ENTITYNO;

                string strDefaultAttachPath = Url.Content("~/" + GenerateUtil.GetConfigValue("DummyPath") + "/" + "Publish/" + entityNo + "/" + "attach/FTP/" + FFTPType + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0'));
                string url = Server.MapPath(strDefaultAttachPath);
                //如果不存在该文件夹就创建
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }
                bool hasfile = false;
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    if (Request.Files[i].ContentLength > 0)
                    {
                        hasfile = true;
                    }
                }
                if (!hasfile)
                {
                    ftpBLL.Delete(f.FID);
                    ViewData["jsAlert"] = "上传失败";
                    Response.Write("<script>alert('上传失败,原因:无文件,请添加上传文件');window.location.href='/Index/LoginUpload/';</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
                System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
                int j = 0;
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    //上传附件
                    if (Request.Files[i].ContentLength > 0 && (uploadFiles.GetKey(i).ToUpper().Contains("UPLOADNAME")))
                    {
                        HttpPostedFileBase upload = Request.Files[i];
                        string type = upload.ContentType;//获取文件类型
                        string extension = Path.GetExtension(upload.FileName).ToLower();
                        long ia = 1;
                        foreach (byte b in Guid.NewGuid().ToByteArray())
                        {
                            ia *= ((int)b + 1);
                        }
                        string result = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + string.Format("{0:x}", ia - DateTime.Now.Ticks);
                        string fullpath = url + @"\" + result + extension;
                        if (System.IO.File.Exists(fullpath) == true)
                        {
                            ftpBLL.Delete(f.FID);
                            ViewData["jsAlert"] = "上传失败";
                            Response.Write("<script>alert('上传失败文件已存在');window.close();</script>");
                            Response.Flush();
                            Response.End();
                            return null;
                            //文件已存在

                        }
                        upload.SaveAs(fullpath);
                        try
                        {
                            ;
                            string strAttachPath = strDefaultAttachPath + "/" + result + extension;
                            string factFileName = Path.GetFileNameWithoutExtension(upload.FileName);//获取文件名称

                            Model.DocAttach docAttachModel = new Model.DocAttach();
                            //获取文件二进制格式

                            System.IO.Stream stream = upload.InputStream;
                            byte[] buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            stream.Close();
                            string docDesc = "";

                            docAttachModel.FEntityNo = entityNo;
                            docAttachModel.FAttachSvrFileName = strAttachPath;
                            docAttachModel.FAttachOldFileName = factFileName + extension;
                            docAttachModel.FAttachContent = buffer;
                            docAttachModel.FAttachFileExt = type;
                            docAttachModel.FAttachType = "FTP";
                            docAttachModel.FAttachDesc = docDesc;
                            docAttachModel.FAttachSource = f.FID;
                            if (!ftpBLL.InsertdocAttach(docAttachModel, f.FID.ToString()))
                            {
                                ftpBLL.Delete(f.FID);
                            }

                        }
                        catch (Exception ee)
                        {
                            if (System.IO.File.Exists(fullpath) == true)
                            {
                                System.IO.File.Delete(fullpath);
                            }
                            ftpBLL.Delete(f.FID);
                            Response.Write("<script>alert('上传失败错误原因" + ee.Message.ToString() + "');window.close();</script>");
                            Response.Flush();
                            Response.End();
                            return null;
                        }
                    }
                }

                ViewData["jsAlert"] = "上传成功";
                Response.Write("<script>alert('上传成功');window.close();</script>");
                Response.Flush();
                Response.End();

            }
            catch (System.Exception ex)
            {
                Response.Write("<script>alert('上传失败错误原因" + ex.Message.ToString() + "');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
            return null;
        }

        public ActionResult Filelook(string FDeptNo, string FYear = "", string FMOn = "", int id = 1, string FNoAgency="N")
        {
            bool isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            if (string.IsNullOrEmpty(FYear))
            {
                FYear = DateTime.Now.Year.ToString();
            }
            if (string.IsNullOrEmpty(FMOn))
            {
                FMOn = DateTime.Now.Month.ToString();
            }
            List<Model.FTP> ftplists = ftpBLL.GetModelList("");
            DateTime mint = ftplists.Min(p => p.FInputTime);//取最小日期
            int y = DateTime.Now.Year;
            List<string> yeardata = new List<string>();
            for (int i = mint.Year; i < y + 1; i++)//最小日期的年份开始
            {
                yeardata.Add(i.ToString());
            }

            ViewData["YearData"] = yeardata;
            int yout;
            if (!string.IsNullOrEmpty(FYear) & int.TryParse(FYear, out yout))
            {
                ViewData["selYear"] = FYear;
            }
            else
            {
                ViewData["selYear"] = y.ToString();
            }
            List<string> mons = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
            ViewData["MonData"] = mons;
            ViewData["selMon"] = "";
            if (!string.IsNullOrEmpty(FMOn) & int.TryParse(FMOn, out yout))
            {
                ViewData["selMon"] = FMOn;
            }
            else
            {
                ViewData["selMon"] = int.Parse(DateTime.Now.Month.ToString());
            }
            ViewData["dept"] = FDeptNo;
            string entityNo = GlobalConstant.ENTITYNO;
            string FShowContent = HRDeptBLL.GetFShowContent(entityNo, FDeptNo);
            ViewData["FShowContent"] = FShowContent.ToString();
         //string strwhere = " FDeptNo=" + FDeptNo;
         //if (FNoAgency == "Y")
         //{
         //    ViewData["isAgency"] = "Y";
         //    isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;

         //    if (isLogin)
         //    {
         //        string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
         //        if (ftpBLL.FIsAllowLookFtpByEmpNoAndNoAgency(emplNo, entityNo))
         //        {
         //            strwhere = "FDeptNo IN (SELECT FDeptNo FROM dbo.t_HRDept WHERE FIsAgency='N')";
         //        }
         //        else
         //        {

         //            Response.Write("<script>alert('您无权查看市局文件');window.close();</script>");
         //            Response.Flush();
         //            Response.End();
         //            return null;
         //        }
         //    }
         //    else
         //    {

         //        Response.Write("<script>alert('请先登录');window.close();</script>");
         //        Response.Flush();
         //        Response.End();
         //        return null;
         //    }
         //}
          
         //   if (!string.IsNullOrEmpty(FYear) & int.TryParse(FYear, out yout))
         //   {
         //       if (!string.IsNullOrEmpty(FMOn) & int.TryParse(FMOn, out yout))
         //       {
         //           strwhere += " and  DATEDIFF(MM,FInputTime,'" + FYear + "-" + FMOn.PadLeft(2, '0') + "-01')=0";
         //       }
         //       else
         //       {
         //           strwhere += " and  DATEDIFF(YEAR,FInputTime,'" + FYear + "-01-01')=0";
         //       }
         //   }
         //   List<Model.FTP> ftplist = ftpBLL.GetModelList(strwhere).OrderBy(h=>h.FInputTime).Reverse().ToList();
         //   List<Model.FTP> ftplist2 = ftplist.ToList().Skip(id * 20 - 20).Take(20).ToList();
         //   PagedList<Model.FTP> pgftp = new PagedList<Model.FTP>(ftplist2, id, 20, ftplist.Count);
         //   // ViewData["ftplist"] = ftplist;
            ViewData["isall"] = false;
            string strWhere = "1=1";
            if (FNoAgency == "N")
            {

                
              //  if (isLogin)
              //  {
                    string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    string deptno = "";
                    string deptnname = "";
                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                deptno = dt.Rows[i]["FDeptNo"].ToString();
                                deptnname = ViewData["DeptName"].ToString();
                                break;
                            }

                        }
                        
                    }
                    if (deptno == FDeptNo | ftpBLL.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
                    {
                        strWhere += " AND FDeptNo='" + FDeptNo + "' ";
                        ViewData["isall"] = true;
                    } 
                    else
                    {
                        strWhere += " AND FDeptNo='" + FDeptNo + "' ";
                        ViewData["isall"] = false;
                        // return View("Filelook",  new PagedList<Model.FTP_New>( new List<Model.FTP_New>(),0,0,0));
                    }
                //}
                //else
                //{

                //    Response.Write("<script>alert('请先登录');window.close();</script>");
                //    Response.Flush();
                //    Response.End();
                //    return null;
                //}
            }
            else
            {
                ViewData["isAgency"] = "Y";
                strWhere += "AND FDeptNo IN (SELECT FDeptNo from dbo.t_HRDept WHERE FIsAgency='N' )";
                if (isLogin)
                {
                    string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    if (ftpBLL.FIsAllowLookFtpByEmpNoAndNoAgency(emplNo, entityNo)|ftpBLL.FIsAllowLookFtpByEmpNo(emplNo,entityNo))
                    {
                        ViewData["isall"] = true;
                        //strwhere = "FDeptNo IN (SELECT FDeptNo FROM dbo.t_HRDept WHERE FIsAgency='N')";
                    }
                    else
                    {

                        Response.Write("<script>alert('您无权查看市局文件');window.close();</script>");
                        Response.Flush();
                        Response.End();
                        return null;
                    }
                }
                else
                {

                    Response.Write("<script>alert('请先登录');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
            }
            if (!string.IsNullOrEmpty(FYear) & int.TryParse(FYear, out yout))
            {
                if (!string.IsNullOrEmpty(FMOn) & int.TryParse(FMOn, out yout))
                {
                    strWhere += " and  DATEDIFF(MM,FDate,'" + FYear + "-" + FMOn.PadLeft(2, '0') + "-01')=0";
                }
                else
                {
                    strWhere += " and  DATEDIFF(YEAR,FDate,'" + FYear + "-01-01')=0";
                }
            }
            BLL.FTP_New xbll = new BLL.FTP_New();
            strWhere += "and FType='F'";
            var zcxx = xbll.GetVModelList2(strWhere);

            List<Model.FTP_New> ftplist = xbll.DataTableToList(zcxx).OrderBy(h => h.FDate).Reverse().ToList();
            List<Model.FTP_New> ftplist2 = ftplist.ToList().Skip(id * 20 - 20).Take(20).ToList();
            PagedList<Model.FTP_New> pgftp = new PagedList<Model.FTP_New>(ftplist2, id, 20, ftplist.Count);
            return View("Filelook", pgftp);
        }
        public ActionResult DlOne(string ids)
        {
             string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
             if (string.IsNullOrEmpty(emplNo))
             {
                 Response.Write("<script>alert('请先登录');window.close();</script>");
                 Response.Flush();
                 Response.End();
                 return null;
             }
             else
             {

                 string deptno = "";
                 string deptnname = "";
                 DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                 if (ds.Tables[0].Rows.Count > 0)
                 {
                     DataTable dt = ds.Tables[0];
                     for (int i = 0; i < dt.Rows.Count; i++)
                     {
                         if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                         {
                             ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                             ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                             deptno = dt.Rows[i]["FDeptNo"].ToString();
                             deptnname = ViewData["DeptName"].ToString();
                             break;
                         }

                     }

                 }

                 // if (deptno == FDeptNo | ftpBLL.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
                 BLL.FTP ftpoldbll = new BLL.FTP();
                 BLL.FTP_New ftpBLL = new BLL.FTP_New();
                 Model.FTP_New ftpModel = ftpBLL.GetModel(decimal.Parse(ids));
                 if ( ftpoldbll.FIsAllowLookFtpOrAllowByDeptnew(ids,emplNo, entityNo))
                 {
                     string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径
                     string strZipTopDirectoryPath = scxzFilePath;//文件路径
                     if (ftpModel.FParentID != null)
                     {
                         strZipTopDirectoryPath += GetPathByPid(ftpModel.FParentID.Value);
                     }

                     string strFilePath = strZipTopDirectoryPath + ftpModel.FName;

                     return new Common.FileResult() { FilePaht = strFilePath, FileName = ftpModel.FName };
                 }
                 else
                 {
                     Response.Write("<script>alert('您无权下载此文件');window.close();</script>");
                     Response.Flush();
                     Response.End();
                     return null;

                 }
             }
        }
        private string GetPathByPid(decimal pId)
        {
            BLL.FTP_New ftpBLL = new BLL.FTP_New();
            DataTable dtPreFTP = ftpBLL.GetListPre(pId);
            string strPreFTP = "";
            foreach (DataRow row in dtPreFTP.Rows)
            {
                strPreFTP += row["FName"].ToString() + "/";
            }
            return strPreFTP;
        }
        private List<Model.FTP_New> GetFtpList(string FID, string strWhere, int pageSize, out int total, int pageIndex = 1)
        {
            BLL.FTP_New ftpBLL = new BLL.FTP_New();
            total = 0;
            List<Model.FTP_New> ftpList = new List<Model.FTP_New>();
            string fieldOrder = "FID";
            string fields = "*";
            string entityNo = Common.GlobalConstant.ENTITYNO;
            string tableName = "v_FTP";
            if (FID != null)
            {
                strWhere += " AND FEntityNo='" + entityNo + "' AND FParentID='" + FID + "' ";
            }
            else
            {
                strWhere += " AND FEntityNo='" + entityNo + "' ";
            }

            DataSet ds = commonBLL.GetListByPage(tableName, fields, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
            ftpList = ftpBLL.DataTableToList(ds.Tables[0]);

            return ftpList;
        }

        /// <summary>
        /// 图片/列表可切换信息列表
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="keyClass"></param>
        /// <param name="docClsCd"></param>
        /// <param name="id"></param>
        /// <param name="mode">p图片模式，l列表模式</param>
        /// <returns></returns>
        public ActionResult DocPicList(string keyName, string keyClass, string docClsCd = "", int id = 1, string mode = "p")
        {
            string entityNo = GlobalConstant.ENTITYNO;
            int pageSize = 15;
            if (Fetch.Post("hdMode") != null && Fetch.Post("hdMode").ToString() != "")
            {
                mode = Fetch.Post("hdMode").ToString();
            }

            if (mode == "p")
            {
                pageSize = 15;
            }
            else if (mode == "l")
            {
                pageSize = 20;
            }
            ViewData["mode"] = mode;
            ViewData["keyName"] = keyName;
            ViewData["keyClass"] = keyClass;
            int total = 0;
            List<Models.DocumentGridModel> docGridList = GetDocList(keyName, keyClass, pageSize, out total, "N", id, docClsCd);
            PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);
            if (docClsCd != "")
            {
                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                    ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                }
            }
            else
            {
                //if (isShowLeftDiv == "N")
                //{
                Model.Config configModel = configBLL.GetModel(keyName, keyClass, entityNo);
                if (configModel != null)
                {
                    ViewData["docClsName"] = configModel.FShowText;
                    ViewData["navi"] = "当前位置：首页 > " + ViewData["docClsName"].ToString();
                }
                else
                {
                    ViewData["docClsName"] = "";
                    ViewData["navi"] = "";
                }
                //}

            }
            return View(documentList);
        }


        /// <summary>
        /// 获取系统参数(用户单点登录)
        /// </summary>
        private void getParam()
        {
            string action = "/Index/Index";
            string isSSO = "0";
            BLL.SysParam _sysParamBll = new BLL.SysParam();
            Model.SysParam OA_SSOUseModel = _sysParamBll.GetModel("OA_SSOUse", GlobalConstant.ENTITYNO);
            Model.SysParam OA_SSOLoginAddressModel = _sysParamBll.GetModel("OA_SSOLoginAddress", GlobalConstant.ENTITYNO);
            if (OA_SSOUseModel != null && OA_SSOLoginAddressModel != null)
            {
                if (OA_SSOUseModel.FFValue == "Y")
                {
                    action = OA_SSOLoginAddressModel.FFValue;
                    isSSO = "1";
                }
            }

            ViewData["action"] = action;
            ViewData["isSSO"] = isSSO;

        }

        /// <summary>
        /// 门户用户统一登录
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        private string ssoUidLogin(ref string uid)
        {
            string message = string.Empty;
            if (Request.QueryString["token"] != null)
            {
                string tokenEncrypt = Request.QueryString["token"].ToString();
                string _ip = Common.GenerateUtil.GetClientIPv4Address();

                string token = tokenEncrypt;
                string key = "NBSWJSOA";//系统安全码秘钥
                string SecutiryCode = SoaEncrypt.encrypt(key, key);//系统安全码

                SsoService sss = new SsoService();

                if (token != null)
                {
                    SsoUserInfo ssoUserInfoObject = sss.appLogin(token, _ip, SecutiryCode);
                    if (ssoUserInfoObject != null)
                    {
                        string _uid = SoaEncrypt.decrypt(ssoUserInfoObject.token, key);

                        uid = _uid;

                        BLL.PrvUser prvUserBLL = new BLL.PrvUser();
                        if (!prvUserBLL.ExistsBySSOUid(_uid, GlobalConstant.ENTITYNO))
                        {
                            message = "SSOUserBind";
                        }
                        else
                        {
                            //登陆成功处理 

                            //ip控制验证
                            bool _ipcheck = Fetch.IpCheck();

                            if (_ipcheck)
                            {
                                //ip未限制
                                Model.PrvUser userObj = prvUserBLL.GetModelBySSSOUid(_uid, GlobalConstant.ENTITYNO);
                                if (userObj != null)
                                {
                                    if (userObj.FProhibitLogin == 1)
                                    {
                                        message = "banLogin";//禁止登录
                                    }
                                    else if (userObj.FForeverAvailable != 1)//如果账号不是永久有效，就判断该账号是否已过期
                                    {
                                        DateTime timenow = DateTime.Now.AddDays(-1);
                                        if (timenow > userObj.FAvailableDate)//已过期
                                        {
                                            message = "loginPast";
                                        }
                                    }


                                    if (message == string.Empty)
                                    {
                                        OperateSession.add(GlobalConstant.PARAM_LOGINID, userObj.FLogID);//登录ID
                                        OperateSession.add(GlobalConstant.PARAM_FEMPLNO, userObj.FEmplNo);//员工编号
                                        OperateSession.add("EntityNo", userObj.FEntityNo);//公司编号

                                        //获取主岗位部门编号
                                        BLL.HREmplPosition empPositionBll = new BLL.HREmplPosition();
                                        string deptNo = empPositionBll.GetMainPositionDeptNo(userObj.FEmplNo, userObj.FEntityNo);
                                        OperateSession.add(GlobalConstant.PARAM_DEPTNO, deptNo);


                                        //获取主岗位部门名称
                                        BLL.HRDept deptBll = new BLL.HRDept();
                                        string deptName = deptBll.GetDeptName(deptNo, userObj.FEntityNo);
                                        OperateSession.add(GlobalConstant.PARAM_DEPTNAME, deptName);


                                        //获取当前登录人员姓名
                                        BLL.HREmpl emplBll = new BLL.HREmpl();
                                        string empName = emplBll.GetEmpName(userObj.FEntityNo, userObj.FEmplNo);
                                        OperateSession.add(GlobalConstant.PARAM_USERNAME, empName);


                                        //从数据库获取Ntko Office控件序列号
                                        BLL.Entity entityBll = new BLL.Entity();
                                        Model.Entity entityModel = entityBll.GetModel(userObj.FEntityNo);
                                        if (entityModel != null)
                                        {
                                            OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                                            OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                                        }


                                        //更新组织结构表最近登录相关信息
                                        Model.Entity entityObject = new Model.Entity();
                                        entityObject.FEntityNo = userObj.FEntityNo;
                                        entityObject.FLastLoginIPAddr = Request.UserHostAddress;
                                        entityObject.FLogID = userObj.FLogID;
                                        entityObject.FAccessDate = DateTime.Now;
                                        try
                                        {
                                            entityBll.UpdateByEntityNo(entityObject);
                                        }
                                        catch (Exception)
                                        {

                                        }
                                        BLL.PrvUser adminLoginBLL = new BLL.PrvUser();
                                        OperateSession.add(GlobalConstant.PARAM_FEMPLNO, userObj.FEmplNo);
                                        userObj.FLastLoginIPAddr = Common.GenerateUtil.GetClientIPv4Address();
                                        adminLoginBLL.UpdateUserLoginMsg(userObj.FLogID, userObj.FLastLoginIPAddr, userObj.FEmplNo, userObj.FLastLoginIPAddr);



                                        //增加签到日志,用于电子去向牌
                                        //string beginTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
                                        //string endTime = DateTime.Now.ToString();
                                        //if (!entityBll.ExistsSignTime(userObj.FEmplNo, beginTime, endTime))//判断今天是否已签到
                                        //{
                                        //    try
                                        //    {
                                        //        entityBll.AddSignTime(userObj.FEmplNo, DateTime.Now);
                                        //    }
                                        //    catch (Exception)
                                        //    {

                                        //    }
                                        //}

                                        ////如果上午,判断上午是否已签到;如果下午，判断下午是否已签到
                                        //string cutOffTime1 = ConfigurationManager.AppSettings["cutOffTime1"];
                                        //string cutOffTime2 = ConfigurationManager.AppSettings["cutOffTime2"];

                                        //string morningBeginTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
                                        //string morningEndTime = DateTime.Now.ToString("yyyy-MM-dd") + " " + cutOffTime1;
                                        //string noonBeginTime = DateTime.Now.ToString("yyyy-MM-dd") + " " + cutOffTime2;
                                        //string noonEndTime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
                                        //string strNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                        //if (entityBll.IsInTimeDepart(strNowTime, morningBeginTime, morningEndTime))//今天上午
                                        //{
                                        //    if (!entityBll.ExistsSignTimeToSecond(userObj.FEmplNo, morningBeginTime, morningEndTime))
                                        //    {
                                        //        entityBll.AddSignTime(userObj.FEmplNo, DateTime.Now);
                                        //    }
                                        //}
                                        //else if (entityBll.IsInTimeDepart(strNowTime, noonBeginTime, noonEndTime))//今天下午
                                        //{
                                        //    if (!entityBll.ExistsSignTimeToSecond(userObj.FEmplNo, noonBeginTime, noonEndTime))
                                        //    {
                                        //        entityBll.AddSignTime(userObj.FEmplNo, DateTime.Now);
                                        //    }
                                        //}





                                        //增加当前年度，用于绩效考核
                                        //OperateSession.add("PYear", DateTime.Now.Year.ToString());
                                        OperateSession.add("PYear", entityBll.GetCxcsEvlaClassMaxYear(userObj.FEntityNo));


                                        //政府采购相关Session
                                        OperateSession.add("EmplNo", userObj.FEmplNo);
                                        OperateSession.add("year", entityBll.GetGovYear(userObj.FEntityNo).ToString());



                                    }

                                }
                                else
                                {
                                    //Response.Redirect("~/SSOUserBind.aspx?uid=" + _uid);
                                    message = "SSOUserBind";
                                }
                            }
                            else
                            {
                                //Show.showMethod(this, "ip受限制,请联系管理员!", "");
                                message = "ipAstrict";
                            }


                        }
                    }
                }
            }
            else
            {

            }



            return message;
        }

        /// <summary>
        ///  第一次登录用户跟单点登录用户绑定
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public ActionResult SSOUserBind(string uid)
        {
            string message = string.Empty;
            if (string.IsNullOrEmpty(uid))
            {
                message = "empty";
            }

            ViewData["message"] = message;
            ViewData["uid"] = uid;

            return View();
        }


        /// <summary>
        /// 单点用户绑定时直接登录按钮方法
        /// </summary>
        /// <param name="logId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public string DirectLogin(string logId, string password)
        {
            logId = Fetch.estimateString(logId, CheckGetEnum.Safety);
            password = Fetch.estimateString(password, CheckGetEnum.Safety);
            string loginMessage = Login(logId, password);
            if (loginMessage.IndexOf('^') != -1)
            {
                return "ok";
            }
            else
            {
                return loginMessage;
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="logId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public string Login(string logId, string password)
        {
            logId = Fetch.estimateString(logId, CheckGetEnum.Safety);
            password = Fetch.estimateString(password, CheckGetEnum.Safety);
            string val = string.Empty;
            if (logId == string.Empty || password == string.Empty)
            {
                return "用户名或密码不能为空！";
            }
            else
            {

                if (!Fetch.IpCheck())
                {
                    return "原因ip地址限制";//ip限制
                }

                BLL.PrvUser userBll = new BLL.PrvUser();
                Model.PrvUser userObj = userBll.GetModelByNameAndPassword(logId, password, GlobalConstant.ENTITYNO);
                if (null != userObj)
                {

                    if (userObj.FProhibitLogin == 1)
                    {
                        return "banLogin禁止登陆";//禁止登录
                    }
                    else if (userObj.FForeverAvailable != 1)//如果账号不是永久有效，就判断该账号是否已过期
                    {
                        DateTime timenow = DateTime.Now.AddDays(-1);
                        if (timenow > userObj.FAvailableDate)//已过期
                        {
                            return "loginPast账号已过期";
                        }
                    }



                    OperateSession.add(GlobalConstant.PARAM_LOGINID, userObj.FLogID);//登录ID
                    OperateSession.add(GlobalConstant.PARAM_FEMPLNO, userObj.FEmplNo);//员工编号
                    OperateSession.add(GlobalConstant.ENTITYNO, userObj.FEntityNo);//公司编号

                    //获取主岗位部门编号
                    BLL.HREmplPosition empPositionBll = new BLL.HREmplPosition();
                    string deptNo = empPositionBll.GetMainPositionDeptNo(userObj.FEmplNo, userObj.FEntityNo);
                    OperateSession.add(GlobalConstant.PARAM_DEPTNO, deptNo);


                    //获取主岗位部门名称
                    BLL.HRDept deptBll = new BLL.HRDept();
                    string deptName = deptBll.GetDeptName(userObj.FEntityNo, deptNo);
                    OperateSession.add(GlobalConstant.PARAM_DEPTNAME, deptName);


                    //获取当前登录人员姓名
                    BLL.HREmpl emplBll = new BLL.HREmpl();
                    string empName = emplBll.GetEmpName(userObj.FEntityNo, userObj.FEmplNo);
                    OperateSession.add(GlobalConstant.PARAM_USERNAME, empName);


                    //从数据库获取Ntko Office控件序列号
                    BLL.Entity entityBll = new BLL.Entity();
                    Model.Entity entityModel = entityBll.GetModel(userObj.FEntityNo);
                    if (entityModel != null)
                    {
                        OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                        OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                    }


                    //更新组织结构表最近登录相关信息
                    Model.Entity entityObject = new Model.Entity();
                    entityObject.FEntityNo = userObj.FEntityNo;
                    entityObject.FLastLoginIPAddr = Request.UserHostAddress;
                    entityObject.FLogID = userObj.FLogID;
                    entityObject.FAccessDate = DateTime.Now;
                    try
                    {
                        entityBll.UpdateByEntityNo(entityObject);
                    }
                    catch (Exception)
                    {

                    }

                    BLL.PrvUser adminLoginBLL = new BLL.PrvUser();
                    OperateSession.add(GlobalConstant.PARAM_FEMPLNO, userObj.FEmplNo);
                    userObj.FLastLoginIPAddr = Common.GenerateUtil.GetClientIPv4Address();
                    adminLoginBLL.UpdateUserLoginMsg(userObj.FLogID, userObj.FLastLoginIPAddr, userObj.FEmplNo, userObj.FLastLoginIPAddr);

                    ////如果上午,判断上午是否已签到;如果下午，判断下午是否已签到
                    //string cutOffTime1 = ConfigurationManager.AppSettings["cutOffTime1"];
                    //string cutOffTime2 = ConfigurationManager.AppSettings["cutOffTime2"];

                    //string morningBeginTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
                    //string morningEndTime = DateTime.Now.ToString("yyyy-MM-dd") + " " + cutOffTime1;
                    //string noonBeginTime = DateTime.Now.ToString("yyyy-MM-dd") + " " + cutOffTime2;
                    //string noonEndTime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
                    //string strNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    //if (entityBll.IsInTimeDepart(strNowTime, morningBeginTime, morningEndTime))//今天上午
                    //{
                    //    if (!entityBll.ExistsSignTimeToSecond(userObj.FEmplNo, morningBeginTime, morningEndTime))
                    //    {
                    //        entityBll.AddSignTime(userObj.FEmplNo, DateTime.Now);
                    //    }
                    //}
                    //else if (entityBll.IsInTimeDepart(strNowTime, noonBeginTime, noonEndTime))//今天下午
                    //{
                    //    if (!entityBll.ExistsSignTimeToSecond(userObj.FEmplNo, noonBeginTime, noonEndTime))
                    //    {
                    //        entityBll.AddSignTime(userObj.FEmplNo, DateTime.Now);
                    //    }
                    //}




                    //增加当前年度，用于绩效考核
                    //OperateSession.add("PYear", DateTime.Now.Year.ToString());
                    OperateSession.add("PYear", entityBll.GetCxcsEvlaClassMaxYear(userObj.FEntityNo));

                    //政府采购相关Session
                    OperateSession.add("EmplNo", userObj.FEmplNo);
                    OperateSession.add("year", entityBll.GetGovYear(userObj.FEntityNo).ToString());

                    ////写入cookie，用于记住用户和密码
                    //HttpCookie cookie = new HttpCookie(logId);
                    ////可能是中文字符，必须经过编码      
                    //cookie.Value = HttpUtility.UrlEncode(password);
                    //cookie.Expires = DateTime.Now.AddYears(1);
                    //System.Web.HttpContext.Current.Response.Cookies.Add(cookie); 
                    isLogin = true;
                    return empName + "^" + deptName;
                }
                else
                {
                    return "用户名或密码错误请重新填写！";
                }

            }


        }


        /// <summary>
        /// 用户绑定
        /// </summary>
        /// <param name="logId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public string UserBind(string logId, string password)
        {
            logId = Fetch.estimateString(logId, CheckGetEnum.Safety);
            password = Fetch.estimateString(password, CheckGetEnum.Safety);

            BLL.PrvUser userBll = new BLL.PrvUser();
            if (userBll.ExistsSSOUidByLogID(logId, GlobalConstant.ENTITYNO))
            {
                return "ExistsSSOID";//该账户已经绑定，无法再次绑定
            }


            string loginMessage = Login(logId, password);

            if (loginMessage.IndexOf('^') != -1)
            {
                string uid = Fetch.estimateString(Request.Form["uid"], CheckGetEnum.Safety);
                if (uid == string.Empty)
                {
                    loginMessage = "uidError";
                }
                else
                {
                    try
                    {
                        userBll.UpdateUid(logId, GlobalConstant.ENTITYNO, uid);
                        loginMessage = "ok";
                    }
                    catch (Exception)
                    {
                        loginMessage = "uidUpdError";
                    }


                }
            }

            return loginMessage;
        }


        #region 文明台账相关
        /// <summary>
        /// 各部门首页
        /// </summary>
        /// <returns></returns>
        public ActionResult ACCDocumentIndex()
        {
            return View();
        }
        /// <summary>
        /// 信息列表
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="keyClass"></param>
        /// <param name="docClsCd"></param>
        /// <param name="showLeftDiv">是否显示左边的导航树</param>
        /// <returns></returns>
        public ActionResult ACCDocList(string isShowLeftDiv = "N", int id = 1)
        {
            isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            string entityNo = GlobalConstant.ENTITYNO;
            int pageSize = 20;
            int total = 0;
            List<Models.AccManagerDocGridModel> docGridList = GetACCDocList(pageSize, out total, "N", id);
            PagedList<Models.AccManagerDocGridModel> documentList = new PagedList<Models.AccManagerDocGridModel>(docGridList, id, pageSize, total);

            return View(documentList);
        }


        /// <summary>
        ///递归获取目录树(目前只读取一级子目录)
        /// </summary>
        /// <param name="docClsHtml"></param>
        /// <param name="docSubClsList"></param>
        /// <param name="preDocClsNo"></param>
        /// <param name="className"></param>
        private void SetDirIdHtml(string dirId, ref string docClsHtml, DataTable configDocClsDT, string FPreDirId)
        {
            var tmpDocCls = configDocClsDT.Select("FPreDirId='" + FPreDirId + "'").ToList();
            if (tmpDocCls.Count() > 0)
            {
                docClsHtml += "<ul class='sup'>";
                foreach (DataRow dr in tmpDocCls)
                {
                    docClsHtml += "<li><a href='/Index/DocList?dirId=" + dirId +
                                       "&indexDirId=" + dr["FDirId"].ToString()
                                        + "' target='contentFrm' >" + dr["FDirName"].ToString() + "</a></li>";
                    //SetDocClsHtml(docClsHtml, configDocClsDT, dr["FDocClsCd"].ToString());
                }
                docClsHtml += "</ul>";
            }
        }

        /// <summary>
        /// 列表页
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="configClass"></param>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="isHomePage">是否首页</param>
        /// <param name="pageIndex"></param>
        /// <param name="docClsCd"></param>
        /// <returns></returns>
        private List<Models.AccManagerDocGridModel> GetACCDocList(int pageSize, out int total, string isHomePage, int pageIndex = 1)
        {
            total = 0;
            List<Models.AccManagerDocGridModel> documentList = new List<Models.AccManagerDocGridModel>();
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);

            string fieldOrder = " FShowDate";
            if (isLogin)
            {
                //已登录
                //栏目: 1、不控制查看权限 或者 2、控制查看权限，公开标题 或者 3、控制查看权限，不公开标题，有权限
                string strWhere = "";
                string fiedls = "*";
                string tableName = "";
                tableName = "v_accManagerDocDept";
                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                documentList = ViewDataRowToModel.DataTableToListACCDocuemt(ds.Tables[0]);
            }
            else
            {
                //未登录
                //栏目：1、不控制查看权限 或者 2、控制查看权限，公开标题
                string strWhere = "";
                string fiedls = "*";
                string tableName = "";
                tableName = "v_accManagerDocDept";
                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                documentList = ViewDataRowToModel.DataTableToListACCDocuemt(ds.Tables[0]);

            }
            return documentList;
        }





        #endregion




        #region 信息引用相关

        /// <summary>
        /// 信息引用类别选择
        /// </summary>
        /// <returns></returns>
        public ActionResult DocRefImpClsChoose(decimal docID)
        {
            return BindDocRefImpClsChooseData(docID);
        }


        /// <summary>
        /// 绑定信息类别选择数据(信息引用)
        /// </summary>
        /// <param name="docId">信息编号</param>
        /// <returns></returns>
        //private ActionResult BindDocRefImpClsChooseData(decimal docID, string selectMode = "3", bool checkboxMode = true)
        //{
        //    BLL.DocCls docClsBLL = new BLL.DocCls();

        //    string treeJsonStr = "";
        //    treeJsonStr += "[";

        //    //string loginName = OperateSession.get(GlobalConstant.para);
        //    //获取部门信息
        //    string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
        //    string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
        //    string entityNo = GlobalConstant.ENTITYNO;
        //    if (emplNo != null && deptNo != null && entityNo != null)
        //    {
        //        List<Model.DocCls> docClsList = new List<Model.DocCls>();
        //        DataTable authorityDT = docClsBLL.GetListByAuthority(entityNo, emplNo, deptNo, "PUB");
        //        BLL.Document documentBLL = new BLL.Document();
        //        Model.Document documentModel = documentBLL.GetModel(docID);//获取本信息
        //        for (int i = 0; i < authorityDT.Rows.Count; i++)
        //        {
        //            if (authorityDT.Rows[i]["FDocClsCd"].ToString() != documentModel.FDocClsCd)
        //            {
        //                DataRow dr = authorityDT.Rows[i];
        //                Model.DocCls docClsModel = new Model.DocCls()
        //                {
        //                    FDocClsCd = dr["Fdocclscd"].ToString(),
        //                    FPreDocClsCd = dr["fpredocclscd"].ToString(),
        //                    FDocClsProp = dr["fdocclsprop"].ToString(),
        //                    FDocClsName = dr["fdocclsname"].ToString(),
        //                    //IsAuthority = dr["fisauthority"].ToString(),
        //                    //FSeq = dr["FSeq"] == null ? 0 : int.Parse(dr["FSeq"].ToString())
        //                };
        //                docClsList.Add(docClsModel);
        //            }
        //        }
        //        if (docClsList.Count > 0)
        //        {
        //            //List<Model.docCls> docClsFirstList = (from m in docClsList
        //            //                                      where m.FPreDocClsCd == ""
        //            //                                      select m).OrderBy(s => s.FSeq).ToList();
        //            List<Model.DocCls> docClsFirstList = (from m in docClsList
        //                                                  where m.FPreDocClsCd == ""
        //                                                  select m).ToList();

        //            foreach (Model.DocCls docClsModel in docClsFirstList)
        //            {
        //                //List<Model.docCls> tmpModelList = (from m in docClsList
        //                //                                   where m.FPreDocClsCd == docClsModel.FDocClsCd
        //                //                                   select m).OrderBy(s => s.FSeq).ToList();
        //                List<Model.DocCls> tmpModelList = (from m in docClsList
        //                                                   where m.FPreDocClsCd == docClsModel.FDocClsCd
        //                                                   select m).ToList();

        //                int childCount = tmpModelList.Count;
        //                if (childCount > 0)
        //                {
        //                    treeJsonStr += "{'title':'" + docClsModel.FDocClsName + "','key':'" + docClsModel.FDocClsCd + "','expand':true,'isFolder':true,'activate':true,'icon':''";
        //                    treeJsonStr += ",'children':[";
        //                    GetChildDocClsList(tmpModelList, docClsList, ref treeJsonStr);

        //                    treeJsonStr += "]";


        //                }
        //                else
        //                {
        //                    treeJsonStr += "{'title':'" + docClsModel.FDocClsName + "','key':'" + docClsModel.FDocClsCd + "','expand':true,'isFolder':false,'activate':true,'icon':''";

        //                }
        //                treeJsonStr += "},";
        //            }

        //        }
        //        treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        //        treeJsonStr += "]";
        //        treeJsonStr = treeJsonStr.Replace("\\", "");
        //        treeJsonStr = treeJsonStr.Replace("'", "\"");
        //        ViewData["treeJsonStr"] = treeJsonStr;
        //        ViewData["treeSelectMode"] = selectMode;
        //        ViewData["checkboxMode"] = checkboxMode.ToString().ToLower();
        //        return View("DocRefImpClsChoose");
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}
        private ActionResult BindDocRefImpClsChooseData(decimal docID, string selectMode = "3", bool checkboxMode = true)
        {
            BLL.DocCls docClsBLL = new BLL.DocCls();

            string treeJsonStr = "";
            treeJsonStr += "[";

            //string loginName = OperateSession.get(GlobalConstant.para);
            //获取部门信息
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string entityNo = GlobalConstant.ENTITYNO;
            if (emplNo != null && deptNo != null && entityNo != null)
            {
                List<Model.DocCls> docClsList = new List<Model.DocCls>();
                BLL.Document documentBLL = new BLL.Document();
                Model.Document documentModel = documentBLL.GetModel(docID);//获取本信息
                DataTable authorityDT = docClsBLL.GetListByAuthority(entityNo, emplNo, deptNo, "PUB", documentModel.FDocId, documentModel.FDocClsCd);
                for (int i = 0; i < authorityDT.Rows.Count; i++)
                {
                    if (authorityDT.Rows[i]["FDocClsCd"].ToString() != documentModel.FDocClsCd)
                    {
                        DataRow dr = authorityDT.Rows[i];
                        Model.DocCls docClsModel = new Model.DocCls()
                        {
                            FDocClsCd = dr["Fdocclscd"].ToString(),
                            FPreDocClsCd = dr["fpredocclscd"].ToString(),
                            FDocClsProp = dr["fdocclsprop"].ToString(),
                            FDocClsName = dr["fdocclsname"].ToString(),
                            //IsAuthority = dr["fisauthority"].ToString(),
                            //FSeq = dr["FSeq"] == null ? 0 : int.Parse(dr["FSeq"].ToString())
                        };
                        docClsList.Add(docClsModel);
                    }
                }
                if (docClsList.Count > 0)
                {
                    //List<Model.docCls> docClsFirstList = (from m in docClsList
                    //                                      where m.FPreDocClsCd == ""
                    //                                      select m).OrderBy(s => s.FSeq).ToList();
                    List<Model.DocCls> docClsFirstList = (from m in docClsList
                                                          where m.FPreDocClsCd == ""
                                                          select m).ToList();

                    foreach (Model.DocCls docClsModel in docClsFirstList)
                    {
                        //List<Model.docCls> tmpModelList = (from m in docClsList
                        //                                   where m.FPreDocClsCd == docClsModel.FDocClsCd
                        //                                   select m).OrderBy(s => s.FSeq).ToList();
                        List<Model.DocCls> tmpModelList = (from m in docClsList
                                                           where m.FPreDocClsCd == docClsModel.FDocClsCd
                                                           select m).ToList();

                        int childCount = tmpModelList.Count;
                        if (childCount > 0)
                        {
                            treeJsonStr += "{'title':'" + docClsModel.FDocClsName + "','key':'" + docClsModel.FDocClsCd + "','expand':true,'isFolder':true,'activate':true,'icon':''";
                            treeJsonStr += ",'children':[";
                            GetChildDocClsList(tmpModelList, docClsList, ref treeJsonStr);

                            treeJsonStr += "]";


                        }
                        else
                        {
                            treeJsonStr += "{'title':'" + docClsModel.FDocClsName + "','key':'" + docClsModel.FDocClsCd + "','expand':true,'isFolder':false,'activate':true,'icon':''";

                        }
                        treeJsonStr += "},";
                    }

                }
                treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                treeJsonStr += "]";
                treeJsonStr = treeJsonStr.Replace("\\", "");
                treeJsonStr = treeJsonStr.Replace("'", "\"");
                ViewData["treeJsonStr"] = treeJsonStr;
                ViewData["treeSelectMode"] = selectMode;
                ViewData["checkboxMode"] = checkboxMode.ToString().ToLower();
                return View("DocRefImpClsChoose");
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 递归获取栏目树
        /// </summary>
        /// <param name="docClsChildList"></param>
        /// <param name="docClsList"></param>
        /// <param name="treeJsonStr"></param>
        private void GetChildDocClsList(List<Model.DocCls> docClsChildList, List<Model.DocCls> docClsList, ref string treeJsonStr)
        {
            foreach (Model.DocCls docClsModel in docClsChildList)
            {
                List<Model.DocCls> tmpModelList = (from m in docClsList
                                                   where m.FPreDocClsCd == docClsModel.FDocClsCd
                                                   select m).OrderBy(s => s.FSeq).ToList();

                int childCount = tmpModelList.Count;
                if (childCount > 0)
                {
                    treeJsonStr += "{'title':'" + docClsModel.FDocClsName + "','key':'" + docClsModel.FDocClsCd + "','expand':true,'isFolder':true,'activate':true,'icon':''";
                    treeJsonStr += ",'children':[";
                    GetChildDocClsList(tmpModelList, docClsList, ref treeJsonStr);

                    treeJsonStr += "]";
                }
                else
                {
                    treeJsonStr += "{'title':'" + docClsModel.FDocClsName + "','key':'" + docClsModel.FDocClsCd + "','expand':true,'isFolder':false,'activate':true,'icon':''";

                }
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }

        public string AddDocRefImp(string docId, string docClsList)
        {
            BLL.DocRefImp docRefImpBLL = new BLL.DocRefImp();
            string returnValue = "";
            try
            {
                List<CommonValueModel> docClsObjects = JsonConvert.DeserializeObject<List<CommonValueModel>>(docClsList);

                List<Model.DocRefImp> docRefImpList = new List<Model.DocRefImp>();
                foreach (CommonValueModel valueModel in docClsObjects)
                {
                    Model.DocRefImp docRefImpModel = new Model.DocRefImp();
                    docRefImpModel.FDocId = decimal.Parse(docId.Trim());
                    docRefImpModel.FDocClsCd = valueModel.Value;
                    docRefImpModel.FEntityNo = GlobalConstant.ENTITYNO;
                    docRefImpModel.FImpEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    docRefImpModel.FImpDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);

                    docRefImpList.Add(docRefImpModel);
                }

                docRefImpBLL.AddDocRefImp(docRefImpList);
                returnValue = "SUCCESS";
            }
            catch (Exception ex)
            {
                returnValue = ex.ToString();
            }

            return returnValue;
        }

        public ActionResult ShowError(string message)
        {
            ViewData["message"] = message;
            return View();
        }
        #endregion




    }
}
